Skip to content

feat(executor): serve the Commands gRPC service - #2775

Merged
blkt merged 1 commit into
mainfrom
feat/2695-commands-server
Nov 16, 2026
Merged

blkt merged 1 commit into
mainfrom
feat/2695-commands-server

Conversation

@blkt

@blkt blkt commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Adds the executor Commands gRPC server for #2695 as a separate mecatl-executor serve -listen ADDR mode. The one-shot Pod exec mode (no arguments) is unchanged until #2718.

What changes

  • internal/executorrpc/commandserver adapts a small Runner interface to the CommandService bidirectional stream: start validation, timeout capped at the server limit, started first, stdout/stderr streamed under a combined output cap (output_truncated), in-band cancel that still returns a result, and succeeded / failed / cancelled / timed out / outcome unknown. A half-close does not cancel; closing the call kills the command.
  • internal/executionexecutor.CommandSupervisor runs each command under its own helper process (mecatl-executor supervise-command), a child subreaper that reuses today's process-group kill and reap-until-ECHILD cleanup. Commands can run concurrently without reaping each other's descendants. Unconfirmed cleanup, a missing or unparsable helper report, or a helper that does not report in time after cancellation yields OUTCOME_UNKNOWN. The server is itself a subreaper and reaps orphans of killed helpers.
  • internal/executorrpc/commandconformance drives any CommandServiceClient through harness-supplied scenarios: exit status, streaming before exit with in-band cancel, timeout, half-close, closing the call with a background child, outcome unknown, invalid starts. It runs against a scripted runner on every platform and against the real supervisor on Linux, and is shaped so In-memory implementation of Files and Commands #2691 can plug in.
  • A new depguard rule limits internal/executorrpc to the standard library, engine, the executor contract, gRPC and protobuf (no os, no syscall), following Files gRPC server #2694's import rule.

Nothing under engine/ or contracts/ changes. The wire contract is the one defined in #2764; this PR only implements it.

Not in this PR

Testing

  • Linux tests (supervisor conformance, background-child kill on call close, survivor yields outcome unknown, minimal environment and identity, concurrent command isolation, orphan reaper) pass with -race -count=3 in a golang:1.27.3 linux/arm64 container as a non-root user.
  • go test -race on ./internal/executorrpc/... passes on macOS.
  • task lint: clean except environment/microvm/launch_ownership_darwin.go:754 (gosec G703), which is pre-existing on main and untouched here.
  • task test:race has not been run locally; leaving it to CI.

Refs #2695

@blkt blkt self-assigned this Nov 16, 2026
@blkt
blkt force-pushed the feat/2695-commands-server branch from a7baec6 to 7412eb5 Compare November 16, 2026 08:11
@blkt
blkt marked this pull request as ready for review November 16, 2026 08:12
@blkt

blkt commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

Sequence diagrams for the new Commands server flow.

1. Serve mode startup

sequenceDiagram
    participant M as main()
    participant R as runServeMode
    participant X as executionexecutor
    participant G as grpc.Server
    M->>R: os.Args[1:] = ["serve", "-listen", addr]
    R->>X: EnableCommandExecution() (server becomes subreaper)
    R->>R: net.Listen(addr)
    R->>X: NewCommandSupervisor(["/proc/self/exe", "supervise-command"], env=[], /workspace)
    R->>R: commandserver.New(supervisor, WithMaxTimeout, WithMaxOutputBytes, WithMaxCommandBytes)
    R-)X: go supervisor.ReapOrphans(ctx, 1s)
    R->>G: RegisterCommandServiceServer, Serve(lis)
    Note over M,G: SIGINT/SIGTERM cancels ctx → srv.Stop() (WaitForHandlers)
Loading

2. A command that succeeds

sequenceDiagram
    participant C as Client
    participant S as Server.RunCommand
    participant P as CommandSupervisor (server process)
    participant H as Helper process (supervise-command)
    participant Sh as /bin/sh -c
    C->>S: RunCommandRequest{Start{command, timeout}}
    S->>S: validate → timeout = min(requested, max)
    S->>S: runCtx = WithTimeoutCause(streamCtx+cancelCause, timeout, errTimedOut)
    S->>P: Start(runCtx, command, stdoutWriter, stderrWriter)
    P->>H: fork/exec /proc/self/exe supervise-command<br/>fd0=control, fd1/fd2=output pipes, fd3=status
    H->>H: EnableCommandExecution() (helper becomes subreaper)
    P->>H: control: length-prefixed command
    H->>Sh: start (Setpgid, minimal env, dir=/workspace)
    H->>P: status: "started\n"
    P-->>S: Process
    S->>C: Started
    S-)S: go receiveCancel(stream)
    loop while the shell writes
        Sh->>P: stdout/stderr bytes (pipes go straight to the server)
        P->>S: streamWriter.Write
        S->>C: Stdout / Stderr chunks (≤32 KiB, combined cap)
    end
    Sh-->>H: exit 0
    H->>H: SIGKILL process group, kill+reap reparented children until ECHILD (≤2s)
    H->>P: status: "exit 0 true\n", then helper exits
    P->>P: Wait(): parse status, drain output, reap helper
    P-->>S: Exit{Code 0, Confirmed true}
    S->>C: Result{SUCCEEDED, exit 0, truncated?}
Loading

3. In-band cancel, timeout, or closing the call

All three end runCtx; only the recorded cause differs.

sequenceDiagram
    participant C as Client
    participant S as Server.RunCommand
    participant P as CommandSupervisor
    participant H as Helper
    participant Sh as /bin/sh + descendants
    alt in-band cancel
        C->>S: RunCommandRequest{Cancel}
        S->>S: receiveCancel: cancel(errCancelRequested)
    else timeout
        S->>S: deadline fires: cause errTimedOut
    else client closes the call
        C--xS: stream context ends
    end
    Note over S,P: runCtx.Done()
    P->>H: control: one byte
    H->>Sh: SIGKILL process group + shell
    H->>Sh: kill+reap every reparented descendant until ECHILD (≤2s)
    H->>P: status: "exit CODE true"
    P-->>S: Exit{Confirmed true}
    alt call still open
        S->>C: Result{CANCELLED or TIMED_OUT}
    else call closed
        Note over S,C: nothing to send to, but the command is still killed
    end
Loading

A client half-close (CloseSend) is io.EOF in receiveCancel and does not cancel.

4. Cleanup cannot be confirmed → OUTCOME_UNKNOWN

sequenceDiagram
    participant S as Server.RunCommand
    participant P as CommandSupervisor
    participant H as Helper
    participant D as Surviving descendant
    participant RO as ReapOrphans (server, every 1s)
    alt helper reports unproven cleanup
        H->>H: reap loop hits 2s without ECHILD
        H->>P: status: "exit CODE false"
    else helper silent / unparsable / dead
        P->>P: no valid line within helperStopTimeout after cancel
    end
    P->>H: SIGKILL helper
    Note over H,D: helper dies → D reparents to the nearest subreaper: the server
    P->>P: drain output pipes (≤1s deadline), reap helper
    P-->>S: Exit{Confirmed false}
    S->>S: classify: !Confirmed → OUTCOME_UNKNOWN (beats every other state)
    RO->>D: D is a child of the server but not a registered helper → SIGKILL, Wait4
Loading

5. One-shot Pod exec mode (unchanged behaviour, shared cleanup)

sequenceDiagram
    participant K as Pod exec (stdin JSON)
    participant E as mecatl-executor (no args)
    participant Sh as /bin/sh -c
    K->>E: request
    E->>E: EnableCommandExecution() (main.go:60)
    E->>Sh: runIsolatedCommand → runShell (same code the helper uses)
    Sh-->>E: exit
    E->>E: kill group, reap until ECHILD
    E->>K: response JSON
Loading

@rdimitrov rdimitrov 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.

Overall this is solid. Half-close vs. cancel, timeout capping, the combined output cap, per-command subreaper isolation and the Start/ReapOrphans locking all check out. There's one real bug, and two things I'd fix before the transport switch relies on this.

1. The command inherits the helper's status pipe on fd 3 and can forge its own result.
cmd/mecatl-executor/main.go wraps fd 3 with os.NewFile(3, "status"). The fd comes in through ExtraFiles, so it isn't close-on-exec, and runShell never sets the flag. As a result, /bin/sh and everything it spawns inherit the write end.

  • In a linux container with the real supervisor, echo 'exit 0 true' >&3; sleep 1; exit 7 comes back as SUCCEEDED with exit code 0.
  • It also breaks the kill path. Once Wait reads the forged line it closes p.finished, and the ctx watcher in Start stops. With echo 'exit 0 true' >&3; sleep 3600, timeout and cancel no longer kill the command, and cleanup is reported as confirmed.
  • Fix: call syscall.CloseOnExec(3) in the helper before running the shell, and add a Linux test that the command only sees fds 0–2.

2. Output can reach the client before started.
The supervisor starts its stdout/stderr copy goroutines inside Start, but the server only sends started after Start returns. A fast command like printf x can therefore send a stdout event first, which breaks the "started first" contract that commandconformance.start() asserts. The window is tiny, so expect a rare flake rather than a reproducible failure. Either send started before the copiers can call Send, or hold output in the writer until it has gone out.

3. NO_SHELL can't be produced by the real supervisor.
server.go maps tool.ErrNoShell to FailedPrecondition/NO_SHELL, but CommandSupervisor.Start never returns it. With /bin/sh missing, the helper's cmd.Start fails, it exits without writing started, and the client gets Internal "command did not start". Only the scripted runner exercises that branch today. Either report the missing shell back through the helper, or drop the mapping until it's wired.

(The CodeQL alert is on internal/adapter/server/authn.go, which this PR doesn't touch.)

Add a `serve` mode to `cmd/mecatl-executor` that runs the
`mecatl.executor.v1` CommandService. The one-shot Pod exec mode (no
arguments) is unchanged until #2718.

`internal/executorrpc/commandserver` adapts a small `Runner` interface to
the bidirectional stream: it validates the start, caps the timeout at the
server limit, sends `started`, streams stdout and stderr bounded by a
combined output limit, honors an in-band cancel, and reports succeeded,
failed, cancelled, timed out, or outcome unknown. Output written before
`started` is held until it is sent. Closing the call kills the command. A depguard rule keeps it, and the conformance suite, to
engine, the executor contract, and gRPC, so #2716 is a move.

`internal/executionexecutor.CommandSupervisor` runs each command under its
own helper process (`mecatl-executor supervise-command`), a child
subreaper that reuses the existing process-group kill and reap-until-ECHILD
cleanup. A per-command subreaper keeps every descendant attributable while
other commands run concurrently. The helper reports whether cleanup was
confirmed; anything else, including a helper that does not report in time
after cancellation, is outcome unknown. The server is itself a subreaper
and kills and reaps orphans of killed helpers. The helper's status pipe
is close-on-exec, and both the helper and the server are non-dumpable,
so a command can reach its status neither by inheritance nor through
/proc. A missing shell is reported as NO_SHELL.

`internal/executorrpc/commandconformance` drives any CommandService client
through harness-supplied scenarios (exit status, streaming before exit,
in-band cancel, timeout, closing the call with a background child, outcome
unknown, invalid starts). It runs against a scripted runner here and
against the real supervisor on Linux, and is shaped for #2691.

Mutual TLS, per-service flags, and the Files service follow in their own
issues.

Refs #2695
@blkt
blkt force-pushed the feat/2695-commands-server branch from 7412eb5 to b88ffe9 Compare November 16, 2026 10:05

@rdimitrov rdimitrov 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 three are addressed:

  • The status fd is now close-on-exec, and the helper and server are non-dumpable. The new tests cover the inherited fd, /proc-based forging, and the timeout bypass.
  • Output is held until started goes out, and the held bytes still count against the combined cap.
  • A missing shell now comes back as noshell and reaches the client as NO_SHELL, with a Linux test.

LGTM once CI goes green.

@blkt
blkt enabled auto-merge (squash) November 16, 2026 10:24
@blkt
blkt merged commit 5a988d6 into main Nov 16, 2026
50 checks passed
@blkt
blkt deleted the feat/2695-commands-server branch November 16, 2026 10:30
@toolhive-release-app toolhive-release-app Bot mentioned this pull request Nov 18, 2026
2 tasks
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.

2 participants