Repository navigation
feat(executorrpc): add a Files and Commands client for the agent loop - #2863
Conversation
Add `internal/executorrpc/executorclient`, which implements `tool.Workspace`, `tool.WorkspaceNamespace`, `tool.AuthorityResourceResolver`, and a foreground `tool.CommandRunner` over the executor `FileService` and `CommandService`. It works against the trusted service or a local executor, and imports only `engine`, the generated executor contract, and gRPC. Each call builds its full `RequestContext` through a per-call function and sends it in the opaque context. Calls are sent once, and `Dial` always disables gRPC retries. A command stream that fails after the start confirmation, or a result of `COMMAND_STATE_OUTCOME_UNKNOWN`, returns `ErrOutcomeUnknown` and is never retried; ending the caller's context sends a cancel and still waits for the result. `fileconformance` drops its own minimal `Workspace` and runs the `FileService` conformance suites through this client, so `fileserver`, `memexecutor`, and `mecatl-executor serve` are all checked through it. `executionclient.NewTemplateProvider` gains `WithExecutorServices`, which serves run environments through the new client on the same pinned mTLS connection. It stays off until the provider proxies these services in the transport switch. The remote workspace conformance and file-tool tests now run over both transports. Refs: #2710
rdimitrov
left a comment
There was a problem hiding this comment.
LGTM as an off-by-default step. Retries are disabled in a way callers can't override, the command is sent on exactly one stream, the authority path is checked against the root, and the read protocol checks (data after version, no version) are good. Running fileconformance through this client is a nice way to cover the server and the client together.
Two things I'd want settled before #2718 turns WithExecutorServices() on (inline). Neither blocks this PR.
| started := false | ||
| for { | ||
| msg, err := stream.Recv() | ||
| if err != nil && !started { |
There was a problem hiding this comment.
On the "did not start" window you flagged in the description: I think the client can already tell these apart. Every refusal that commandserver makes before runner.Start returns a handler status (validation errors, NO_SHELL with FailedPrecondition, Internal "command did not start"). The window you're worried about, where the process starts and then sending Started fails, can only show up on the client as a transport-level code: Unavailable, Canceled, DeadlineExceeded, or Unknown.
So before started, treating those transport codes as ErrOutcomeUnknown and only the rest as notStarted would close the gap. "Did not start" reads to the model as safe to retry, and a non-idempotent command (a git push, a migration) could then run twice.
There was a problem hiding this comment.
This should be addressed, could you have a look?
There was a problem hiding this comment.
Looks good. A failure before Started now counts as "not started" only when the executor tagged it as a refusal (validation, LIMIT_EXCEEDED, NO_SHELL, the new START_FAILED); anything else is ErrOutcomeUnknown. Requiring an explicit Started event instead of any first message, and the supervisor's failed vs. handshake timeout split, close the server side of it too. Thanks.
| if version != nil { | ||
| return nil, tool.FileVersion{}, fmt.Errorf("%w: data after version", errProtocol) | ||
| } | ||
| data = append(data, msg.GetData()...) |
There was a problem hiding this comment.
The client trusts the server to bound the read: data grows for as long as chunks arrive. The same applies to stdout/stderr in receive. When this talks directly to an executor, that server sits in the workload Pod, which is the less trusted side. A cap on the client side at the max file size (and at the max output size for commands) would keep a misbehaving or compromised executor from growing memory in the agent loop. It's a cheap check, and it makes the client stand on its own instead of relying on the server's limits.
There was a problem hiding this comment.
This should be addressed, could you have a look?
There was a problem hiding this comment.
The mechanism looks right: reads fail with ErrLimitExceeded before appending, and command output is truncated with a marker. One follow-up before #2718 turns this on: the only production caller (executionclient/client.go NewWorkspace/NewRunner) passes no options, so the effective cap is the 256 MiB default, about 50x the 5 MiB the server enforces. Since the client now sends calls concurrently, that's 256 MiB per call. Passing WithMaxFileBytes/WithMaxOutputBytes from the template's limits (or executionenv.MaxFileBytes) there would make the cap meaningful. Not blocking.
Address review on the executor client: - A failure before `Started` is outcome unknown unless the server reported a refusal. Transport codes (`Unavailable`, `Canceled`, `DeadlineExceeded`, `Unknown`) and a clean end can follow a process that started, so they no longer read as "did not start", which the model treats as safe to retry. Only `Started` counts as the start confirmation; output before it is a protocol violation. - `Workspace` fails a read over `WithMaxFileBytes` with `ErrLimitExceeded`, and `Runner` keeps at most `WithMaxOutputBytes` of combined output, still reading until the result so the outcome stays known. Both default to 256 MiB, a ceiling against a misbehaving executor above the servers' own limits. - Output clipped by the client, or flagged `output_truncated` by the server, ends with a truncation marker. Refs: #2710
gRPC maps transport failures such as RST_STREAM to `codes.Internal`, the code `commandserver` used for "command did not start", so a dropped stream before `Started` could report a command that ran as never started. Add `ERROR_REASON_START_FAILED` and send it with that refusal. Before `Started` the client now reports "did not start" only for `InvalidArgument`, `LIMIT_EXCEEDED`, `NO_SHELL`, and `START_FAILED`; anything else is `ErrOutcomeUnknown`. The truncation marker no longer names the executor, since the client cap can clip too, and goes on stderr when stdout is empty.
The supervisor wrote the command to its helper and then treated a status read timeout, read error, or garbled line as "command did not start", although the helper may already have started the shell. With `ERROR_REASON_START_FAILED`, that became a tagged refusal the client trusts as never ran. The helper now writes "failed" when the shell never started. Any other handshake failure after the command is sent returns `commandserver.ErrStartUnknown`, which `commandserver` sends as an untagged `Unknown` status, so the client reports `ErrOutcomeUnknown`.
rdimitrov
left a comment
There was a problem hiding this comment.
Re-approving on the fix commits. Start-failure classification is now correct on both ends, and the client has its own response bounds. One non-blocking follow-up on the default cap is in the workspace.go thread.
Summary
Adds
internal/executorrpc/executorclient, a client of the executorFileServiceandCommandServicethat implementstool.Workspace,tool.WorkspaceNamespace,tool.AuthorityResourceResolver, and a foregroundtool.CommandRunner. It works against the trusted service or a local executor, so the agent loop can use one client for both.RequestContextfrom a per-callRequestContextFuncand sends it in the opaquecontextfield (the first message on streams). A nil func sends an empty context, which an executor ignores. No methods were added toWorkspace,CommandRunner, orCommandStreamer.executorclient.Dialalways setsgrpc.WithDisableRetry, and a command is sent on exactly one stream. A stream that breaks after the start confirmation, or anOUTCOME_UNKNOWNresult, returns the host-sideexecutorclient.ErrOutcomeUnknown. When the caller's context ends, the client sends a cancel and waits up to 30s for the result.Started, the client reports "did not start" only for a refusal the executor tagged:InvalidArgument,LIMIT_EXCEEDED,NO_SHELL, or the newSTART_FAILED. Any other error, including transport errors that gRPC maps toInternal, returnsErrOutcomeUnknown. On the executor side, the command supervisor now reports a start whose handshake with its helper fails after the command was sent ascommandserver.ErrStartUnknown(an untaggedUnknownstatus), instead of "did not start".WithMaxFileBytesfails withErrLimitExceeded, and command output is capped byWithMaxOutputBytes(both 256 MiB by default). Truncated output, whether clipped by the client or flagged withoutput_truncatedby the executor, ends with... [output truncated], on stderr when stdout is empty.fileconformancedrops its own minimalWorkspaceand runs the conformance suites through this client, sofileserver,memexecutor, andmecatl-executor serveare all checked through it.Target.ClientbecomesTarget.Conn.executionclient.NewTemplateProvidergains an opt-inWithExecutorServices(), which builds the run environment's workspace and runner from the new client on the existing pinned mTLS connection, converting the run claim into theRequestContexton every call. It is off by default, andcmd/mecak8sdoes not set it. The remote workspace conformance and file-tool tests inexecutionclientrun over both transports.Issue relationship
Closes #2710
The new client is a target of
files_conformance_test.goalongside the current transport. Making it the only transport, dropping theExecutionProviderServicetarget, and the demo going through it are criteria of the transport switch (#2718), sincemecatl-execution-providerdoes not serveFileServiceorCommandServiceyet.Type of change
Test plan
Baseline checks
task lint)task test:race)go run ./cmd/mecademo): tool call, permission ask and approval, result. The demo runs on localmemfsand does not use the new client.task check:prFocused tests:
TestDroppedConnectionDuringCommandIsUnknownAndNotRetrieddrops the connection mid-command and checks forErrOutcomeUnknownwith one script start over one stream.TestExecutorServicesCarryTheRunClaimchecks the claim fields reach the server.TestFailureBeforeStartedIsUnknownUnlessRefused,TestOutputIsCappedAndTruncationReported, andTestReadOverClientLimitFailscover the start classification and the client caps;TestStartFailurescheckscommandservertags each refusal, andTestStartFailuresAreTaggedOnlyWhenNothingRan(Linux) checks the supervisor's no-shell, failed-exec, and vanished-helper cases.FileServiceconformance suites run the same 130 subtests as onmain, now through the client.Changes
internal/executorrpc/executorclient/Workspace,Runner,Dial,ErrOutcomeUnknown,ErrLimitExceeded, size optionscontracts/proto/mecatl/executor/v1/errors.protoERROR_REASON_START_FAILEDinternal/executorrpc/commandserver/server.goSTART_FAILED;ErrStartUnknownfor a start that may have runinternal/executionexecutor/supervisor_linux.gofailed; other handshake failures areErrStartUnknowninternal/executorrpc/fileconformance/conformance.goWorkspace;Target.Conninternal/adapter/executionclient/client.goWithExecutorServices(),runContext.executorContextinternal/adapter/executionclient/files_conformance_test.gointernal/executorrpc/fileserver,memexecutor,cmd/mecatl-executortestsTarget.ConnchangeUser-facing change
None. The new path is off by default.
API compatibility
ErrorReasongainsERROR_REASON_START_FAILED = 9, whichcommandservernow attaches to its existingInternal"command did not start" status; the code and message are unchanged. A start that may have run now returnsUnknowninstead ofInternal. A client that does not know the value sees an unrecognized enum in the detail and behaves as before. Nothing outside this repo consumesmecatl.executor.v1yet.executionclientkeeps callingExecutionProviderServiceunlessWithExecutorServices()is set, and no binary sets it.fileconformance.Target.ClientbecomesTarget.Conn, andfileconformance.Dialreturns a*grpc.ClientConn. Both are internal test helpers whose in-repo callers are updated.Special notes for reviewers
These need settling before #2718 turns the option on:
workspacerefreshed the lease and retried read-only calls once after a definitive auth denial. The new path only reads the current claim, because the proxy's denial code is not defined yet.workspaceheldopMubecause the provider allows one active operation. The new client sends calls concurrently, which assumes the proxy accepts concurrent calls.