From 1c43934e530d0d791a3104242dab4dc5f90025d9 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 17 Sep 2026 17:04:49 +0800 Subject: [PATCH] perf(sandbox): reduce redundant remote calls --- internal/agent/tools/output_links.go | 6 +- internal/agent/tools/output_links_test.go | 55 ++++- internal/agent/tools/shell_exec.go | 35 ++- internal/agent/tools/workspace_reader.go | 1 + .../application/service/artifact_collector.go | 1 + .../service/pinned_session_sandbox.go | 13 ++ .../sandbox_operation_requests_test.go | 165 ++++++++++++++ .../service/workspace_checkpointer.go | 22 +- internal/sandbox/cube_mock_test.go | 4 + internal/sandbox/cube_remote_client.go | 19 ++ internal/sandbox/docker_remote_client.go | 8 + internal/sandbox/e2b_remote_client.go | 34 ++- internal/sandbox/langfuse.go | 12 + internal/sandbox/remote_client.go | 8 + internal/sandbox/session_connect.go | 38 ++++ internal/sandbox/session_connect_test.go | 128 +++++++++++ internal/sandbox/session_file_operation.go | 29 +++ .../sandbox/session_file_operation_test.go | 115 ++++++++++ internal/sandbox/session_lifecycle.go | 23 +- internal/sandbox/session_manager.go | 149 ++++++++++--- .../sandbox/session_shell_snapshot_test.go | 210 ++++++++++++++++++ 21 files changed, 994 insertions(+), 81 deletions(-) create mode 100644 internal/application/service/sandbox_operation_requests_test.go create mode 100644 internal/sandbox/session_connect.go create mode 100644 internal/sandbox/session_connect_test.go create mode 100644 internal/sandbox/session_file_operation.go create mode 100644 internal/sandbox/session_file_operation_test.go create mode 100644 internal/sandbox/session_shell_snapshot_test.go diff --git a/internal/agent/tools/output_links.go b/internal/agent/tools/output_links.go index 35a421bf..ef30e9de 100644 --- a/internal/agent/tools/output_links.go +++ b/internal/agent/tools/output_links.go @@ -27,13 +27,17 @@ func sandboxOutputSnapshot(ctx context.Context, executor SandboxCommandExecutor, if err != nil { return nil, false } + return outputEntriesSnapshot(entries), true +} + +func outputEntriesSnapshot(entries []sandbox.RemoteDirEntry) map[string]sandbox.RemoteDirEntry { files := make(map[string]sandbox.RemoteDirEntry, len(entries)) for _, entry := range entries { if entry.Type == sandbox.RemoteEntryFile { files[entry.Path] = entry } } - return files, true + return files } func changedOutputLinks(before, after map[string]sandbox.RemoteDirEntry) []string { diff --git a/internal/agent/tools/output_links_test.go b/internal/agent/tools/output_links_test.go index 90d49548..e3f3eb67 100644 --- a/internal/agent/tools/output_links_test.go +++ b/internal/agent/tools/output_links_test.go @@ -20,6 +20,58 @@ type outputLinkExecutor struct { listed int } +type combinedOutputExecutor struct { + outputLinkExecutor + snapshot *sandbox.ShellOutputSnapshot + opts sandbox.ShellExecOptions + command string + outputDir string +} + +func (f *combinedOutputExecutor) ExecShellCommandWithOutputSnapshot( + _ context.Context, _, command string, opts sandbox.ShellExecOptions, outputDir string, +) (*sandbox.ExecuteResult, *sandbox.ShellOutputSnapshot, error) { + f.calls++ + f.opts, f.command, f.outputDir = opts, command, outputDir + return &sandbox.ExecuteResult{Stdout: "hello", ExitCode: 0}, f.snapshot, nil +} + +func TestShellOutputLinksPreferCombinedExecution(t *testing.T) { + t.Setenv("WEKNORA_SKILL_OUTPUT_DIR", "/workspace/output") + for _, tc := range []struct { + name string + snapshot *sandbox.ShellOutputSnapshot + want []string + }{ + {"changed", &sandbox.ShellOutputSnapshot{ + Before: []sandbox.RemoteDirEntry{{Path: "/workspace/output/old.txt", Type: sandbox.RemoteEntryFile}}, + After: []sandbox.RemoteDirEntry{ + {Path: "/workspace/output/old.txt", Type: sandbox.RemoteEntryFile}, + {Path: "/workspace/output/new.txt", Type: sandbox.RemoteEntryFile}, + }, + }, []string{"sandbox:new.txt"}}, + {"empty", &sandbox.ShellOutputSnapshot{}, []string{}}, + {"unavailable", nil, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + executor := &combinedOutputExecutor{snapshot: tc.snapshot} + result, err := NewShellExecTool(executor, nil).Execute(shellExecTestContext(), json.RawMessage( + `{"command":"cat", "stdin":"hello\n", "work_dir":"/tmp/task", + "timeout_sec":10, "env":{"KEY":"value"}}`)) + require.NoError(t, err) + require.True(t, result.Success) + require.Equal(t, tc.want, result.OutputFiles) + require.Equal(t, 1, executor.calls) + require.Zero(t, executor.listed, "must not perform legacy scans around the combined operation") + require.Equal(t, "/workspace/output", executor.outputDir) + require.Equal(t, "/tmp/task", executor.opts.WorkDir) + require.Equal(t, 10*time.Second, executor.opts.Timeout) + require.Equal(t, "value", executor.opts.Env["KEY"]) + require.Contains(t, executor.command, "base64 -d") + }) + } +} + func (f *outputLinkExecutor) ListSessionFiles(_ context.Context, sessionID, dir string) ([]sandbox.RemoteDirEntry, error) { f.listed++ if f.listError != nil { @@ -39,7 +91,8 @@ func TestShellOutputLinksUseChangedFilesAndDoNotReplay(t *testing.T) { unchanged := sandbox.RemoteDirEntry{Path: "/workspace/output/data.json", Type: sandbox.RemoteEntryFile, Size: 20} executor := &outputLinkExecutor{ before: []sandbox.RemoteDirEntry{old, unchanged}, - after: []sandbox.RemoteDirEntry{next, unchanged, + after: []sandbox.RemoteDirEntry{ + next, unchanged, {Path: "/workspace/output/new.csv", Type: sandbox.RemoteEntryFile}, {Path: "/workspace/output/subdir", Type: sandbox.RemoteEntryDir}, }, diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.go index 17e8aff4..5afc6434 100644 --- a/internal/agent/tools/shell_exec.go +++ b/internal/agent/tools/shell_exec.go @@ -491,12 +491,37 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ execCommand = "printf %s " + sandbox.ShellQuote(base64.StdEncoding.EncodeToString([]byte(input.Stdin))) + " | base64 -d | /bin/bash --noprofile --norc -c " + sandbox.ShellQuote(execCommand) } - beforeOutputs, inspectedOutputs := sandboxOutputSnapshot(ctx, t.executor, sessionID) output, finishOutput := shellCommandOutput(ctx, command) defer finishOutput() // Observe only the requested command, not skill staging or artifact probes. execCtx := sandbox.WithCommandOutput(ctx, output) - res, err := t.executor.ExecShellCommand(execCtx, sessionID, execCommand, workDir, timeout, env) + var res *sandbox.ExecuteResult + var err error + var outputFiles []string + if executor, ok := t.executor.(interface { + ExecShellCommandWithOutputSnapshot( + context.Context, string, string, sandbox.ShellExecOptions, string, + ) (*sandbox.ExecuteResult, *sandbox.ShellOutputSnapshot, error) + }); ok { + var snapshot *sandbox.ShellOutputSnapshot + res, snapshot, err = executor.ExecShellCommandWithOutputSnapshot(execCtx, sessionID, execCommand, + sandbox.ShellExecOptions{WorkDir: workDir, Timeout: timeout, Env: env}, skills.ArtifactOutputDir()) + if snapshot != nil { + outputFiles = changedOutputLinks( + outputEntriesSnapshot(snapshot.Before), outputEntriesSnapshot(snapshot.After), + ) + } + } else { + // Keep support for executors without the combined operation (including + // install mode); production session managers use one handle above. + before, inspected := sandboxOutputSnapshot(ctx, t.executor, sessionID) + res, err = t.executor.ExecShellCommand(execCtx, sessionID, execCommand, workDir, timeout, env) + if err == nil && res != nil && inspected { + if after, ok := sandboxOutputSnapshot(ctx, t.executor, sessionID); ok { + outputFiles = changedOutputLinks(before, after) + } + } + } finishOutput() noteSandboxMutation() if err != nil { @@ -566,12 +591,6 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ b.WriteString(hint) b.WriteString("\n") } - var outputFiles []string - if inspectedOutputs { - if afterOutputs, ok := sandboxOutputSnapshot(ctx, t.executor, sessionID); ok { - outputFiles = changedOutputLinks(beforeOutputs, afterOutputs) - } - } visibleOutput := b.String() visibleOutput, totalTruncated := truncateShellStream(visibleOutput, maxShellExecVisibleBytes) truncated = truncated || errorTruncated || totalTruncated diff --git a/internal/agent/tools/workspace_reader.go b/internal/agent/tools/workspace_reader.go index b01b1099..97f996bc 100644 --- a/internal/agent/tools/workspace_reader.go +++ b/internal/agent/tools/workspace_reader.go @@ -151,6 +151,7 @@ func (t *workspaceFileReader) read(ctx context.Context, input ReadFileInput) (*t rootDir = "/" } + ctx = sandbox.WithSessionFileOperation(ctx) stat, err := t.source.StatSessionFile(ctx, sessionID, clean) if err != nil { logger.Warnf(ctx, "[Tool][ReadSandboxFile] stat failed: session=%s path=%s err=%v", diff --git a/internal/application/service/artifact_collector.go b/internal/application/service/artifact_collector.go index 59cb0a45..18b6d5d8 100644 --- a/internal/application/service/artifact_collector.go +++ b/internal/application/service/artifact_collector.go @@ -306,6 +306,7 @@ func (c *ArtifactCollector) collect( logger.Infof(ctx, "[ArtifactCollector] begin session=%s dir=%s", sessionID, outputDir) + ctx = sandbox.WithSessionFileOperation(ctx) entries, err := source.ListSessionFiles(ctx, sessionID, outputDir) if err != nil { logger.Warnf(ctx, "[ArtifactCollector] list sandbox files failed: session=%s dir=%s err=%v", diff --git a/internal/application/service/pinned_session_sandbox.go b/internal/application/service/pinned_session_sandbox.go index 48f6916f..7bb69a3f 100644 --- a/internal/application/service/pinned_session_sandbox.go +++ b/internal/application/service/pinned_session_sandbox.go @@ -92,6 +92,19 @@ func (a *PinnedSessionSandbox) ExecShellCommand( return runner.ExecShellCommand(ctx, sessionID, command, workDir, timeout, env) } +// ExecShellCommandWithOptions forwards maintenance options to the pinned +// manager, preserving lookup-only execution and the expected sandbox identity. +func (a *PinnedSessionSandbox) ExecShellCommandWithOptions( + ctx context.Context, sessionID, command string, opts sandbox.ShellExecOptions, +) (*sandbox.ExecuteResult, error) { + mgr := a.manager(ctx, sessionID) + runner, ok := mgr.(sandbox.SessionInstallShellExecutor) + if !ok || runner == nil { + return nil, errors.New("sandbox: no maintenance shell runner for session") + } + return runner.ExecShellCommandWithOptions(ctx, sessionID, command, opts) +} + // HasActiveTurn reports whether the session's pinned manager currently holds a // turn lease. Managers that do not expose the method are treated as not busy. func (a *PinnedSessionSandbox) HasActiveTurn(ctx context.Context, sessionID string) (bool, error) { diff --git a/internal/application/service/sandbox_operation_requests_test.go b/internal/application/service/sandbox_operation_requests_test.go new file mode 100644 index 00000000..234f6d67 --- /dev/null +++ b/internal/application/service/sandbox_operation_requests_test.go @@ -0,0 +1,165 @@ +package service + +import ( + "context" + "encoding/json" + "path" + "strings" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/agent/tools" + "github.com/Tencent/WeKnora/internal/sandbox" + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" +) + +// Only the expected operations are implemented. Accidentally adding lifecycle +// Get/Create calls to lookup-only paths fails rather than hiding extra RPCs. +type operationRequestClient struct { + sandbox.RemoteSandboxClient + ops []string + files map[string][]byte + stat *sandbox.RemoteStatEntry + exec sandbox.RemoteExecRequest +} + +type operationRequestHandle struct{ id string } + +func (h operationRequestHandle) ID() string { return h.id } +func (h operationRequestHandle) Provider() sandbox.SandboxType { return sandbox.SandboxTypeCube } +func (h operationRequestHandle) Metadata() map[string]string { return nil } + +func (c *operationRequestClient) Provider() sandbox.SandboxType { return sandbox.SandboxTypeCube } +func (c *operationRequestClient) Capabilities() sandbox.RemoteSandboxCapabilities { + return sandbox.RemoteSandboxCapabilities{ + SupportsReconnect: true, SupportsMetadata: true, SupportsListSandboxes: true, + SupportsFilesystemEnumeration: true, + } +} + +func (c *operationRequestClient) Connect( + _ context.Context, req sandbox.RemoteConnectRequest, +) (sandbox.RemoteSandboxHandle, error) { + c.ops = append(c.ops, "connect") + return operationRequestHandle{req.SandboxID}, nil +} + +func (c *operationRequestClient) Stat( + _ context.Context, _ sandbox.RemoteSandboxHandle, path string, +) (*sandbox.RemoteStatEntry, error) { + c.ops = append(c.ops, "stat") + if c.stat != nil { + return c.stat, nil + } + return &sandbox.RemoteStatEntry{Path: path, Type: sandbox.RemoteEntryFile, Size: int64(len(c.files[path]))}, nil +} + +func (c *operationRequestClient) ReadFile( + _ context.Context, _ sandbox.RemoteSandboxHandle, path string, +) ([]byte, error) { + c.ops = append(c.ops, "read") + return c.files[path], nil +} + +func (c *operationRequestClient) ListDir( + _ context.Context, _ sandbox.RemoteSandboxHandle, _ string, +) ([]sandbox.RemoteDirEntry, error) { + c.ops = append(c.ops, "list") + entries := make([]sandbox.RemoteDirEntry, 0, len(c.files)) + for filePath, data := range c.files { + entries = append(entries, sandbox.RemoteDirEntry{ + Name: path.Base(filePath), Path: filePath, Type: sandbox.RemoteEntryFile, Size: int64(len(data)), + }) + } + return entries, nil +} + +func (c *operationRequestClient) Exec( + _ context.Context, _ sandbox.RemoteSandboxHandle, req sandbox.RemoteExecRequest, +) (*sandbox.RemoteExecResult, error) { + c.ops = append(c.ops, "exec") + c.exec = req + return &sandbox.RemoteExecResult{Stdout: strings.Repeat("a", 40) + "\n"}, nil +} + +type operationSessionChecker struct{} + +func (operationSessionChecker) SessionExists(context.Context, sandbox.SessionSandboxKey) (bool, error) { + return true, nil +} + +func newOperationRequestManager(t *testing.T) (context.Context, *sandbox.SessionBoundManager, *operationRequestClient) { + t.Helper() + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(42)) + store := sandbox.NewMemorySessionSandboxBindingStore() + _, err := store.Create(ctx, sandbox.SessionSandboxKey{TenantID: 42, SessionID: "s1"}, sandbox.SessionSandboxBinding{ + Version: sandbox.SessionSandboxBindingVersion, Provider: sandbox.SandboxTypeCube, + TenantID: 42, SessionID: "s1", SandboxID: "sb1", TemplateID: "template", CreatedAt: time.Now(), + }) + require.NoError(t, err) + client := &operationRequestClient{files: map[string][]byte{ + "/workspace/output/a.txt": []byte("first"), + "/workspace/output/b.txt": []byte("second"), + }} + cfg := sandbox.DefaultConfig() + cfg.CubeTemplate = "template" + mgr, err := sandbox.NewSessionBoundManager(sandbox.SessionBoundManagerConfig{ + Config: cfg, Client: client, Store: store, Checker: operationSessionChecker{}, SkipHealthProbe: true, + }) + require.NoError(t, err) + return ctx, mgr, client +} + +func TestReadFileReusesConnectionButRefreshesNextCall(t *testing.T) { + ctx, mgr, client := newOperationRequestManager(t) + ctx = tools.WithToolExecContext(ctx, &tools.ToolExecContext{SessionID: "s1"}) + reader := tools.NewReadFileTool(mgr) + result, err := reader.Execute(ctx, json.RawMessage(`{"path":"output/a.txt"}`)) + require.NoError(t, err) + require.True(t, result.Success) + require.Contains(t, result.Output, "first") + require.Equal(t, []string{"connect", "stat", "read"}, client.ops) + + client.ops = nil + result, err = reader.Execute(ctx, json.RawMessage(`{"path":"output/a.txt"}`)) + require.NoError(t, err) + require.True(t, result.Success) + require.Equal(t, []string{"connect", "stat"}, client.ops, + "page cache avoids downloads, but each call still checks the live sandbox") + + client.ops = nil + client.stat = &sandbox.RemoteStatEntry{Type: sandbox.RemoteEntryFile, Size: 9 << 20} + result, err = reader.Execute(ctx, json.RawMessage(`{"path":"output/b.txt"}`)) + require.NoError(t, err) + require.False(t, result.Success) + require.Equal(t, []string{"connect", "stat"}, client.ops, "oversize files must not be downloaded") +} + +func TestArtifactCollectorUsesOneConnectionForAllFiles(t *testing.T) { + ctx, mgr, client := newOperationRequestManager(t) + collector := NewArtifactCollector(mgr, &fakeFileService{}, &fakeStore{}, nil, ArtifactCollectorConfig{}) + artifacts, err := collector.Collect(ctx, "s1", "m1", 42, "/workspace/output") + require.NoError(t, err) + require.Len(t, artifacts, 2) + require.Equal(t, []string{"connect", "list", "read", "read"}, client.ops) + client.ops = nil + _, err = collector.Collect(ctx, "s1", "m2", 42, "/workspace/output") + require.NoError(t, err) + require.Equal(t, []string{"connect", "list", "read", "read"}, client.ops, + "a new collection must not reuse an old handle") +} + +func TestPinnedCheckpointSkipsWorkspacePreparation(t *testing.T) { + ctx, mgr, client := newOperationRequestManager(t) + pinned := NewPinnedSessionSandbox(stubPinReader{configID: "cfg1"}, &stubTenantSandboxResolver{mgr: mgr}, nil) + checkpoint := NewWorkspaceCheckpointer(pinned).Checkpoint(ctx, "s1", "sb1", "m1") + require.NotNil(t, checkpoint) + require.Equal(t, "sb1", checkpoint.SandboxID) + require.Equal(t, strings.Repeat("a", 40), checkpoint.CommitSHA) + require.Equal(t, []string{"connect", "exec"}, client.ops) + require.Equal(t, workspaceCheckpointTimeout, client.exec.Timeout) + require.Equal(t, sandbox.SessionWorkspaceRoot, client.exec.WorkDir) + require.Contains(t, client.exec.Command, "--allow-empty") + require.NotContains(t, client.exec.Command, "mkdir") +} diff --git a/internal/application/service/workspace_checkpointer.go b/internal/application/service/workspace_checkpointer.go index 17a82334..c2222f44 100644 --- a/internal/application/service/workspace_checkpointer.go +++ b/internal/application/service/workspace_checkpointer.go @@ -106,14 +106,20 @@ func (c *WorkspaceCheckpointer) Checkpoint( return nil } - result, err := c.runner.ExecShellCommand( - ctx, - sessionID, - checkpointScript(sandbox.SessionWorkspaceRoot, messageID), - sandbox.SessionWorkspaceRoot, - workspaceCheckpointTimeout, - nil, - ) + var result *sandbox.ExecuteResult + var err error + command := checkpointScript(sandbox.SessionWorkspaceRoot, messageID) + if runner, ok := c.runner.(sandbox.SessionInstallShellExecutor); ok { + // Git operates on the existing workspace. Do not prepare artifact/input + // directories or let a late checkpoint provision a replacement sandbox. + result, err = runner.ExecShellCommandWithOptions(ctx, sessionID, command, sandbox.ShellExecOptions{ + WorkDir: sandbox.SessionWorkspaceRoot, Timeout: workspaceCheckpointTimeout, + SkipWorkspacePrep: true, ExpectedSandboxID: sandboxID, + }) + } else { + result, err = c.runner.ExecShellCommand(ctx, sessionID, command, + sandbox.SessionWorkspaceRoot, workspaceCheckpointTimeout, nil) + } if err != nil { logger.Warnf(ctx, "[WorkspaceCheckpointer] exec failed session=%s message=%s: %v", sessionID, messageID, err) diff --git a/internal/sandbox/cube_mock_test.go b/internal/sandbox/cube_mock_test.go index c23ce312..6ec06606 100644 --- a/internal/sandbox/cube_mock_test.go +++ b/internal/sandbox/cube_mock_test.go @@ -25,6 +25,8 @@ type cubeMockServer struct { server *httptest.Server mu sync.Mutex createBody map[string]any + connectCount atomic.Int32 + infoCount atomic.Int32 createCount atomic.Int32 killCount atomic.Int32 nextID atomic.Int64 @@ -101,6 +103,7 @@ func (m *cubeMockServer) handle(w http.ResponseWriter, r *http.Request) { case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/timeout") && r.Method == http.MethodPost: m.handleSetTimeout(w, r) case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/connect") && r.Method == http.MethodPost: + m.connectCount.Add(1) m.handleConnect(w, r) case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/snapshots") && r.Method == http.MethodPost: m.handleCreateSnapshot(w, r) @@ -109,6 +112,7 @@ func (m *cubeMockServer) handle(w http.ResponseWriter, r *http.Request) { case strings.HasPrefix(r.URL.Path, "/templates/") && r.Method == http.MethodDelete: m.handleDeleteSnapshot(w, r) case strings.HasPrefix(r.URL.Path, "/sandboxes/") && r.Method == http.MethodGet: + m.infoCount.Add(1) m.handleGetInfo(w, r) case strings.HasPrefix(r.URL.Path, "/sandboxes/") && r.Method == http.MethodDelete: m.handleDelete(w, r) diff --git a/internal/sandbox/cube_remote_client.go b/internal/sandbox/cube_remote_client.go index ac40b396..e5ac26e7 100644 --- a/internal/sandbox/cube_remote_client.go +++ b/internal/sandbox/cube_remote_client.go @@ -781,6 +781,25 @@ func (c *CubeRemoteClient) Connect( return &cubeRemoteHandle{sb: sb}, nil } +// ConnectSession reuses the connected SDK handle for the lifecycle probe. +func (c *CubeRemoteClient) ConnectSession(ctx context.Context, req RemoteConnectRequest) (RemoteSandboxHandle, error) { + handle, err := c.Connect(ctx, req) + if err != nil { + return nil, err + } + info, err := handle.(*cubeRemoteHandle).sb.GetInfo(ctx) + if err != nil { + return nil, normalizeCubeError("ConnectSession", err) + } + if info == nil { + return nil, NewRemoteError(SandboxTypeCube, "ConnectSession", RemoteErrorKindNotFound, "sandbox not found", nil) + } + if err := validateSessionSummary(c.Provider(), req.SandboxID, cubeRemoteSummary(*info)); err != nil { + return nil, err + } + return handle, nil +} + func (c *CubeRemoteClient) Get( ctx context.Context, sandboxID string, diff --git a/internal/sandbox/docker_remote_client.go b/internal/sandbox/docker_remote_client.go index 1213bf0b..b927eedb 100644 --- a/internal/sandbox/docker_remote_client.go +++ b/internal/sandbox/docker_remote_client.go @@ -419,6 +419,14 @@ func (c *DockerRemoteClient) Connect( }, nil } +// ConnectSession already gets the lifecycle state from Connect's container +// inspection, including terminal detection and resuming a stopped container. +func (c *DockerRemoteClient) ConnectSession( + ctx context.Context, req RemoteConnectRequest, +) (RemoteSandboxHandle, error) { + return c.Connect(ctx, req) +} + // dockerStartReadyTimeout bounds how long Create/Connect/Exec wait for PID 1 // after the daemon has accepted a start. The window is milliseconds on a // healthy daemon; this is only the ceiling for a wedged one. diff --git a/internal/sandbox/e2b_remote_client.go b/internal/sandbox/e2b_remote_client.go index e1f8b6aa..ff7a8870 100644 --- a/internal/sandbox/e2b_remote_client.go +++ b/internal/sandbox/e2b_remote_client.go @@ -667,18 +667,28 @@ func (c *E2BRemoteClient) Connect( return &e2bRemoteHandle{sandbox: sandbox}, nil } -// Get returns a single sandbox summary by ID. E2B's control plane exposes no -// read-only "fetch sandbox by ID" endpoint, so Get reattaches to the sandbox -// via Connect and reads its full metadata through the per-sandbox info -// endpoint (GET /sandboxes/{id}). This mirrors the Cube adapter's -// Connect+GetInfo shape and yields a strongly-consistent, O(1) lookup with a -// clean NotFound, instead of scanning the whole account-wide sandbox list -// (which is O(N) and can return a stale NotFound for a just-created sandbox). -// -// Get's only caller is the lifecycle coordinator's connectBinding pre-check, -// which Connects — and therefore wakes — the sandbox immediately afterwards. -// Resuming a paused sandbox here is thus the intended behaviour, not a side -// effect to avoid. +// ConnectSession reuses the connected SDK handle for the lifecycle probe. +func (c *E2BRemoteClient) ConnectSession(ctx context.Context, req RemoteConnectRequest) (RemoteSandboxHandle, error) { + handle, err := c.Connect(ctx, req) + if err != nil { + return nil, err + } + info, err := handle.(*e2bRemoteHandle).sandbox.InfoWithContext(ctx) + if err != nil { + return nil, normalizeE2BError("ConnectSession", err) + } + if info == nil { + return nil, NewRemoteError(SandboxTypeE2B, "ConnectSession", RemoteErrorKindNotFound, "sandbox not found", nil) + } + summary := e2bRemoteSummary(*info) + if err := validateSessionSummary(c.Provider(), req.SandboxID, &summary); err != nil { + return nil, err + } + return handle, nil +} + +// Get returns a single sandbox summary through Connect and the info endpoint. +// Session execution uses ConnectSession to retain that handle after probing. func (c *E2BRemoteClient) Get( ctx context.Context, sandboxID string, diff --git a/internal/sandbox/langfuse.go b/internal/sandbox/langfuse.go index afdea8d1..1e13caba 100644 --- a/internal/sandbox/langfuse.go +++ b/internal/sandbox/langfuse.go @@ -72,6 +72,18 @@ func (c *langfuseRemoteClient) Connect( return handle, err } +func (c *langfuseRemoteClient) ConnectSession( + ctx context.Context, req RemoteConnectRequest, +) (RemoteSandboxHandle, error) { + ctx, span := startSandboxSpan(ctx, "sandbox.connect", map[string]interface{}{ + "sandbox_id": req.SandboxID, + "check_state": true, + }, nil) + handle, err := connectRemoteSession(ctx, c.inner, req) + span.Finish(sandboxHandleOut(handle), nil, err) + return handle, err +} + func (c *langfuseRemoteClient) Get( ctx context.Context, sandboxID string, ) (*RemoteSandboxSummary, error) { diff --git a/internal/sandbox/remote_client.go b/internal/sandbox/remote_client.go index fa2498de..9d81e40e 100644 --- a/internal/sandbox/remote_client.go +++ b/internal/sandbox/remote_client.go @@ -49,6 +49,14 @@ type RemoteConnectRequest struct { TrafficAccessToken string } +// RemoteSessionConnector connects and checks lifecycle state using the same +// provider handle. It avoids Get (which itself connects on Cube/E2B) followed +// by another Connect. Terminal/missing sandboxes must return classified errors; +// transient failures must never authorize replacement of a session's sandbox. +type RemoteSessionConnector interface { + ConnectSession(context.Context, RemoteConnectRequest) (RemoteSandboxHandle, error) +} + // RemoteTimeoutMode describes how the remote provider should treat the // requested idle timeout. type RemoteTimeoutMode string diff --git a/internal/sandbox/session_connect.go b/internal/sandbox/session_connect.go new file mode 100644 index 00000000..50fe9769 --- /dev/null +++ b/internal/sandbox/session_connect.go @@ -0,0 +1,38 @@ +package sandbox + +import ( + "context" + "fmt" +) + +func connectRemoteSession( + ctx context.Context, client RemoteSandboxClient, req RemoteConnectRequest, +) (RemoteSandboxHandle, error) { + if connector, ok := client.(RemoteSessionConnector); ok { + return connector.ConnectSession(ctx, req) + } + // Compatibility for providers that do not offer a combined connect/probe. + summary, err := client.Get(ctx, req.SandboxID) + if err != nil { + return nil, err + } + if err := validateSessionSummary(client.Provider(), req.SandboxID, summary); err != nil { + return nil, err + } + return client.Connect(ctx, req) +} + +func validateSessionSummary(provider RemoteProvider, id string, summary *RemoteSandboxSummary) error { + if summary == nil { + return NewRemoteError(provider, "ConnectSession", RemoteErrorKindInternal, + "provider returned no sandbox summary", nil) + } + if summary.ID != id { + return NewRemoteError(provider, "ConnectSession", RemoteErrorKindInternal, + fmt.Sprintf("provider returned sandbox %q for binding %q", summary.ID, id), nil) + } + if summary.State == RemoteStateTerminal { + return NewRemoteError(provider, "ConnectSession", RemoteErrorKindTerminal, "sandbox is terminal", nil) + } + return nil +} diff --git a/internal/sandbox/session_connect_test.go b/internal/sandbox/session_connect_test.go new file mode 100644 index 00000000..93be418b --- /dev/null +++ b/internal/sandbox/session_connect_test.go @@ -0,0 +1,128 @@ +package sandbox + +import ( + "context" + "testing" + "time" + + "github.com/moby/moby/api/types/container" + "github.com/stretchr/testify/require" +) + +func TestCubeSessionConnectReusesProbeHandle(t *testing.T) { + mock := newCubeMockServer(t) + client := newTestCubeRemoteClient(t, mock) + ctx := context.Background() + created, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"}) + require.NoError(t, err) + handle, err := connectRemoteSession(ctx, wrapLangfuseRemoteClient(client), RemoteConnectRequest{ + SandboxID: created.ID(), TrafficAccessToken: "restored-token", + }) + require.NoError(t, err) + require.Equal(t, created.ID(), handle.ID()) + require.Equal(t, "restored-token", InboundTokenOf(handle)) + require.EqualValues(t, 1, mock.connectCount.Load()) + require.EqualValues(t, 1, mock.infoCount.Load()) + + _, err = client.ConnectSession(ctx, RemoteConnectRequest{SandboxID: "gone"}) + require.True(t, CanReplaceRemoteBinding(err)) +} + +func TestE2BSessionConnectReusesProbeHandleAndResumes(t *testing.T) { + mock := newE2BMockServer(t) + client := newTestE2BRemoteClient(t, mock) + ctx := context.Background() + created, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"}) + require.NoError(t, err) + mock.sandboxes[created.ID()]["state"] = "paused" + handle, err := connectRemoteSession(ctx, wrapLangfuseRemoteClient(client), RemoteConnectRequest{ + SandboxID: created.ID(), TrafficAccessToken: "restored-token", + }) + require.NoError(t, err) + require.Equal(t, created.ID(), handle.ID()) + require.Equal(t, "restored-token", InboundTokenOf(handle)) + require.EqualValues(t, 1, mock.connectCount.Load()) + require.EqualValues(t, 1, mock.infoCount.Load()) + require.Equal(t, "running", mock.sandboxes[created.ID()]["state"]) + + _, err = client.ConnectSession(ctx, RemoteConnectRequest{SandboxID: "gone"}) + require.True(t, CanReplaceRemoteBinding(err)) +} + +func TestDockerSessionConnectInspectsOnlyOnce(t *testing.T) { + engine := newFakeDockerEngine() + inspections := 0 + engine.inspectHook = func(id string) (container.InspectResponse, error) { + inspections++ + return container.InspectResponse{ID: id, State: &container.State{Status: "running"}}, nil + } + client := newTestDockerClient(t, engine) + handle, err := connectRemoteSession(context.Background(), wrapLangfuseRemoteClient(client), + RemoteConnectRequest{SandboxID: "container-1"}) + require.NoError(t, err) + require.Equal(t, "container-1", handle.ID()) + require.Equal(t, 1, inspections) +} + +type sessionConnectFaultClient struct { + *fakeRemoteClient + err error + calls int +} + +func (c *sessionConnectFaultClient) ConnectSession( + ctx context.Context, req RemoteConnectRequest, +) (RemoteSandboxHandle, error) { + c.calls++ + if c.err != nil { + return nil, c.err + } + return c.Connect(ctx, req) +} + +func TestCombinedSessionConnectOnlyReplacesDefinitiveFailures(t *testing.T) { + for _, kind := range []RemoteErrorKind{ + RemoteErrorKindTerminal, RemoteErrorKindNotFound, RemoteErrorKindUnavailable, + RemoteErrorKindInternal, RemoteErrorKindAuthentication, + } { + t.Run(string(kind), func(t *testing.T) { + ctx := context.Background() + store := NewMemorySessionSandboxBindingStore() + client := &sessionConnectFaultClient{ + fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube), + err: NewRemoteError(SandboxTypeCube, "ConnectSession", kind, "probe failed", nil), + } + key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"} + client.addSandbox("existing", "template-a", RemoteStateTerminal, nil, time.Now()) + _, err := store.Create(ctx, key, validSessionSandboxBinding(key, "existing")) + require.NoError(t, err) + lifecycle := newTestRemoteSessionLifecycle(t, wrapLangfuseRemoteClient(client), store, + &fakeSessionExistenceChecker{exists: true}) + handle, err := lifecycle.Resolve(ctx, key) + if kind == RemoteErrorKindTerminal || kind == RemoteErrorKindNotFound { + require.NoError(t, err) + require.NotEqual(t, "existing", handle.ID()) + require.Equal(t, 1, client.createCount) + } else { + require.Error(t, err) + require.Zero(t, client.createCount) + binding, err := store.Get(ctx, key) + require.NoError(t, err) + require.Equal(t, "existing", binding.SandboxID) + } + require.Equal(t, 1, client.calls) + require.Empty(t, client.getIDs) + }) + } +} + +func TestSessionSummaryValidation(t *testing.T) { + for _, summary := range []*RemoteSandboxSummary{nil, {ID: "wrong"}} { + err := validateSessionSummary(SandboxTypeCube, "bound", summary) + require.Error(t, err) + require.False(t, CanReplaceRemoteBinding(err)) + } + err := validateSessionSummary(SandboxTypeCube, "bound", + &RemoteSandboxSummary{ID: "bound", State: RemoteStateTerminal}) + require.True(t, CanReplaceRemoteBinding(err)) +} diff --git a/internal/sandbox/session_file_operation.go b/internal/sandbox/session_file_operation.go new file mode 100644 index 00000000..3e19b182 --- /dev/null +++ b/internal/sandbox/session_file_operation.go @@ -0,0 +1,29 @@ +package sandbox + +import ( + "context" + "sync" +) + +type sessionFileOperationKey struct{} + +type sessionFileHandleKey struct { + manager *SessionBoundManager + session SessionSandboxKey +} + +type sessionFileOperation struct { + mu sync.Mutex + handles map[sessionFileHandleKey]RemoteSandboxHandle +} + +// WithSessionFileOperation reuses live handles only within one read/collection +// operation. Callers must create a fresh scope for every tool call or collect, +// never store it on a manager or reuse it across turns. A manager and tenant- +// scoped session key identify each handle, so scopes cannot cross backends or +// tenants. Lookup remains non-provisioning and failures are never cached. +func WithSessionFileOperation(ctx context.Context) context.Context { + return context.WithValue(ctx, sessionFileOperationKey{}, &sessionFileOperation{ + handles: make(map[sessionFileHandleKey]RemoteSandboxHandle), + }) +} diff --git a/internal/sandbox/session_file_operation_test.go b/internal/sandbox/session_file_operation_test.go new file mode 100644 index 00000000..43d17834 --- /dev/null +++ b/internal/sandbox/session_file_operation_test.go @@ -0,0 +1,115 @@ +package sandbox + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" +) + +func TestSessionFileOperationConnectsOnceAndScopesHandles(t *testing.T) { + mgr, client := newSessionManagerExecTestHarness(t) + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000)) + _, err := mgr.resolveSession(ctx, "s1") + require.NoError(t, err) + scope := WithSessionFileOperation(ctx) + _, err = mgr.StatSessionFile(scope, "s1", "/tmp/file") + require.NoError(t, err) + _, err = mgr.ReadSessionFile(scope, "s1", "/tmp/file") + require.NoError(t, err) + require.Len(t, client.connectIDs, 1) + + _, err = mgr.ReadSessionFile(WithSessionFileOperation(scope), "s1", "/tmp/file") + require.NoError(t, err) + require.Len(t, client.connectIDs, 2, "a new operation must refresh the connection") + + otherTenant := context.WithValue(scope, types.TenantIDContextKey, uint64(10001)) + _, err = mgr.ReadSessionFile(otherTenant, "s1", "/tmp/file") + require.Error(t, err, "must not reuse another tenant's sandbox") + _, err = mgr.ReadSessionFile(scope, "s2", "/tmp/file") + require.Error(t, err, "must not reuse another session's sandbox") + otherManager, otherClient := newSessionManagerExecTestHarness(t) + _, err = otherManager.ReadSessionFile(scope, "s1", "/tmp/file") + require.Error(t, err, "must not reuse a different backend's handle") + require.Zero(t, otherClient.createCount) + require.Equal(t, 1, client.createCount, "file operations must never provision") +} + +func TestSessionFileOperationConcurrentReadsConnectOnce(t *testing.T) { + mgr, client := newSessionManagerExecTestHarness(t) + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000)) + _, err := mgr.resolveSession(ctx, "s1") + require.NoError(t, err) + scope := WithSessionFileOperation(ctx) + var wg sync.WaitGroup + errs := make(chan error, 8) + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _, err := mgr.ReadSessionFile(scope, "s1", "/tmp/file") + errs <- err + }() + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } + require.Len(t, client.connectIDs, 1) +} + +func TestSessionFileOperationDoesNotCacheFailures(t *testing.T) { + mgr, client := newSessionManagerExecTestHarness(t) + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000)) + handle, err := mgr.resolveSession(ctx, "s1") + require.NoError(t, err) + scope := WithSessionFileOperation(ctx) + client.connectErrs[handle.ID()] = NewRemoteError(SandboxTypeCube, "Connect", + RemoteErrorKindUnavailable, "offline", nil) + _, err = mgr.ReadSessionFile(scope, "s1", "/tmp/file") + require.Error(t, err) + delete(client.connectErrs, handle.ID()) + _, err = mgr.ReadSessionFile(scope, "s1", "/tmp/file") + require.NoError(t, err) + require.Len(t, client.connectIDs, 2) +} + +func TestExpectedSandboxMaintenanceDoesNotPrepareOrProvision(t *testing.T) { + mgr, client := newSessionManagerExecTestHarness(t) + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000)) + handle, err := mgr.resolveSession(ctx, "s1") + require.NoError(t, err) + result, err := mgr.ExecShellCommandWithOptions(ctx, "s1", "git status", ShellExecOptions{ + ExpectedSandboxID: handle.ID(), SkipWorkspacePrep: true, + WorkDir: SessionWorkspaceRoot, Timeout: time.Second, + }) + require.NoError(t, err) + require.True(t, result.IsSuccess()) + require.Len(t, client.connectIDs, 1) + require.Empty(t, client.getIDs) + require.Len(t, client.execRequests, 1) + require.Equal(t, "git status", client.execRequests[0].Command) + + for _, tc := range []struct{ session, expected string }{ + {"s1", "old-sandbox"}, {"missing-session", handle.ID()}, + } { + _, err := mgr.ExecShellCommandWithOptions(ctx, tc.session, "git status", ShellExecOptions{ + ExpectedSandboxID: tc.expected, SkipWorkspacePrep: true, + }) + require.Error(t, err) + } + require.Len(t, client.connectIDs, 1, "do not resume a mismatched sandbox") + require.Len(t, client.execRequests, 1) + require.Equal(t, 1, client.createCount) + + mgr.checker.(*fakeSessionExistenceChecker).setExists(false) + _, err = mgr.ExecShellCommandWithOptions(ctx, "s1", "git status", ShellExecOptions{ + ExpectedSandboxID: handle.ID(), SkipWorkspacePrep: true, + }) + require.ErrorIs(t, err, ErrSandboxSessionDeleted) + require.Len(t, client.execRequests, 1) +} diff --git a/internal/sandbox/session_lifecycle.go b/internal/sandbox/session_lifecycle.go index ea48adf6..a7a1d325 100644 --- a/internal/sandbox/session_lifecycle.go +++ b/internal/sandbox/session_lifecycle.go @@ -240,28 +240,7 @@ func (l *remoteSessionLifecycle) connectBinding( key SessionSandboxKey, binding SessionSandboxBinding, ) (RemoteSandboxHandle, bool, error) { - summary, err := l.client.Get(ctx, binding.SandboxID) - if err != nil { - if CanReplaceRemoteBinding(err) { - return nil, true, nil - } - return nil, false, fmt.Errorf("get bound remote sandbox: %w", err) - } - if summary == nil { - return nil, false, errors.New("remote sandbox Get returned nil summary") - } - if summary.ID != binding.SandboxID { - return nil, false, fmt.Errorf( - "remote sandbox Get returned ID %q for binding %q", - summary.ID, - binding.SandboxID, - ) - } - if summary.State == RemoteStateTerminal { - return nil, true, nil - } - - handle, err := l.client.Connect(ctx, RemoteConnectRequest{ + handle, err := connectRemoteSession(ctx, l.client, RemoteConnectRequest{ SandboxID: binding.SandboxID, TrafficAccessToken: binding.TrafficAccessToken, }) diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.go index b992c4f3..46ef7c71 100644 --- a/internal/sandbox/session_manager.go +++ b/internal/sandbox/session_manager.go @@ -624,7 +624,7 @@ func (m *SessionBoundManager) ListSessionFiles( if err != nil || !ok { return nil, err } - return m.listFilesRecursive(ctx, handle, dir) + return m.walkSessionFiles(ctx, handle, dir) } // StatSessionFile returns metadata for a single file without downloading @@ -703,7 +703,10 @@ func (m *SessionBoundManager) WriteSessionFile( // flags select the installer working-directory allowlist and bootstrap. Both // ordinary and install calls currently execute as root. type ShellExecOptions struct { - OnOutput func(stream string, chunk []byte) + // ExpectedSandboxID makes maintenance lookup-only: never allocate/rebuild, + // and fail if the binding changed since the caller selected this sandbox. + ExpectedSandboxID string + OnOutput func(stream string, chunk []byte) WorkDir string Timeout time.Duration @@ -719,9 +722,8 @@ type ShellExecOptions struct { // AllowSkillsRoot separately selects the installer working-directory scope; // it is not a filesystem boundary for commands running as root. AsRoot bool - // SkipWorkspacePrep omits prepareSessionDirs. Desktop maintenance - // commands use absolute paths and do not write /workspace; the image - // already has that layout. Never set this from a model-authored tool + // SkipWorkspacePrep omits prepareSessionDirs. Desktop maintenance and + // workspace checkpoints operate on an existing layout. Never set this from a model-authored tool // such as shell_exec — agents still need the workspace contract. SkipWorkspacePrep bool } @@ -752,17 +754,43 @@ func (m *SessionBoundManager) ExecShellCommandWithOptions( command string, opts ShellExecOptions, ) (*ExecuteResult, error) { + result, _, err := m.execShellCommandWithOutputSnapshot(ctx, sessionID, command, opts, "") + return result, err +} + +// ShellOutputSnapshot contains two complete metadata listings of the same sandbox. +// A nil snapshot means inspection failed; an empty snapshot means no output files. +type ShellOutputSnapshot struct { + Before []RemoteDirEntry + After []RemoteDirEntry +} + +// ExecShellCommandWithOutputSnapshot resolves the session once for the command +// and both artifact probes. Handles never escape this call or survive a rebuild. +func (m *SessionBoundManager) ExecShellCommandWithOutputSnapshot( + ctx context.Context, sessionID, command string, opts ShellExecOptions, outputDir string, +) (*ExecuteResult, *ShellOutputSnapshot, error) { + clean, ok := ValidatedSessionOutputDir(outputDir) + if !ok { + return nil, nil, errors.New("sandbox: invalid output directory") + } + return m.execShellCommandWithOutputSnapshot(ctx, sessionID, command, opts, clean) +} + +func (m *SessionBoundManager) execShellCommandWithOutputSnapshot( + ctx context.Context, sessionID, command string, opts ShellExecOptions, outputDir string, +) (*ExecuteResult, *ShellOutputSnapshot, error) { if err := m.requireRemoteBackend(); err != nil { - return nil, fmt.Errorf( + return nil, nil, fmt.Errorf( "sandbox: shell_exec requires the remote sandbox provider (current mode: %s)", m.GetType(), ) } if strings.TrimSpace(sessionID) == "" { - return nil, errors.New("sandbox: session_id required for ExecShellCommand") + return nil, nil, errors.New("sandbox: session_id required for ExecShellCommand") } if strings.TrimSpace(command) == "" { - return nil, errors.New("sandbox: command required for ExecShellCommand") + return nil, nil, errors.New("sandbox: command required for ExecShellCommand") } timeout := opts.Timeout if timeout <= 0 { @@ -778,11 +806,41 @@ func (m *SessionBoundManager) ExecShellCommandWithOptions( } workDir, err := cleanSessionWorkDir(workDir, opts.AllowSkillsRoot) if err != nil { - return nil, err + return nil, nil, err } - handle, err := m.resolveSession(ctx, sessionID) - if err != nil { - return nil, err + var handle RemoteSandboxHandle + if opts.ExpectedSandboxID != "" { + key, keyErr := m.sessionKey(ctx, sessionID) + if keyErr != nil { + return nil, nil, keyErr + } + exists, checkErr := m.checker.SessionExists(ctx, key) + if checkErr != nil { + return nil, nil, checkErr + } + if !exists { + return nil, nil, ErrSandboxSessionDeleted + } + var found bool + // Maintenance must recheck the binding even inside a file-operation scope. + handle, found, err = m.lookupSessionHandleForKey(ctx, key, opts.ExpectedSandboxID) + if err != nil { + return nil, nil, err + } + if !found || handle.ID() != opts.ExpectedSandboxID { + return nil, nil, errors.New("sandbox: bound sandbox changed before maintenance command") + } + } else { + handle, err = m.resolveSession(ctx, sessionID) + if err != nil { + return nil, nil, err + } + } + var snapshot *ShellOutputSnapshot + if outputDir != "" { + if before, err := m.snapshotOutputFiles(ctx, handle, outputDir); err == nil { + snapshot = &ShellOutputSnapshot{Before: before} + } } user := DefaultSandboxExecUser if opts.AsRoot { @@ -793,13 +851,13 @@ func (m *SessionBoundManager) ExecShellCommandWithOptions( // Installation owns the skill directory and does not depend on a // writable session workspace (which is cleaned before snapshotting). if err := m.prepareSessionDirs(ctx, handle, user, workDir); err != nil { - return nil, err + return nil, nil, err } } else { if err := m.prepareSessionDirs( ctx, handle, user, SessionInputRoot, SessionOutputRoot, workDir, ); err != nil { - return nil, err + return nil, nil, err } } } @@ -815,7 +873,14 @@ func (m *SessionBoundManager) ExecShellCommandWithOptions( Timeout: timeout, }) duration := time.Since(start) - return remoteExecuteResult(execResult, execErr, duration), nil + if snapshot != nil { + if after, err := m.snapshotOutputFiles(ctx, handle, outputDir); err == nil { + snapshot.After = after + } else { + snapshot = nil + } + } + return remoteExecuteResult(execResult, execErr, duration), snapshot, nil } // SessionShellExecutor advertises the shell-execution capability while the @@ -1208,6 +1273,27 @@ func (m *SessionBoundManager) lookupSessionHandle( if err != nil { return nil, false, err } + // Serialise scope lookups so even concurrent reads connect only once. + // The scope is owned by one operation, not by this long-lived manager. + if scope, ok := ctx.Value(sessionFileOperationKey{}).(*sessionFileOperation); ok { + scope.mu.Lock() + defer scope.mu.Unlock() + cacheKey := sessionFileHandleKey{manager: m, session: key} + if handle := scope.handles[cacheKey]; handle != nil { + return handle, true, nil + } + handle, found, err := m.lookupSessionHandleForKey(ctx, key, "") + if err == nil && found { + scope.handles[cacheKey] = handle + } + return handle, found, err + } + return m.lookupSessionHandleForKey(ctx, key, "") +} + +func (m *SessionBoundManager) lookupSessionHandleForKey( + ctx context.Context, key SessionSandboxKey, expectedID string, +) (RemoteSandboxHandle, bool, error) { binding, err := m.bindings.Get(ctx, key) if err != nil { return nil, false, fmt.Errorf("sandbox: read session binding: %w", err) @@ -1215,6 +1301,9 @@ func (m *SessionBoundManager) lookupSessionHandle( if binding == nil || binding.Provider != m.client.Provider() { return nil, false, nil } + if expectedID != "" && binding.SandboxID != expectedID { + return nil, false, errors.New("sandbox: bound sandbox changed before maintenance command") + } handle, err := m.client.Connect(ctx, RemoteConnectRequest{ SandboxID: binding.SandboxID, TrafficAccessToken: binding.TrafficAccessToken, @@ -1233,22 +1322,19 @@ func (m *SessionBoundManager) lookupSessionHandle( return handle, true, nil } -func (m *SessionBoundManager) listFilesRecursive( - ctx context.Context, - handle RemoteSandboxHandle, - dir string, +// snapshotOutputFiles does not probe with Stat: a missing output directory is +// an empty baseline, while permission and transport errors remain failures. +func (m *SessionBoundManager) snapshotOutputFiles( + ctx context.Context, handle RemoteSandboxHandle, dir string, ) ([]RemoteDirEntry, error) { - stat, err := m.client.Stat(ctx, handle, dir) - if err != nil { - if IsRemoteNotFound(err) { - return nil, nil - } - return nil, fmt.Errorf("sandbox: stat %s: %w", dir, err) - } - if stat == nil { - return nil, nil - } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + return m.walkSessionFiles(ctx, handle, dir) +} +func (m *SessionBoundManager) walkSessionFiles( + ctx context.Context, handle RemoteSandboxHandle, dir string, +) ([]RemoteDirEntry, error) { stack := []string{dir} var files []RemoteDirEntry for len(stack) > 0 { @@ -1257,6 +1343,11 @@ func (m *SessionBoundManager) listFilesRecursive( entries, err := m.client.ListDir(ctx, handle, cur) if err != nil { + // Only a missing root is an empty listing. A vanished subdirectory + // makes this snapshot incomplete and must not publish partial links. + if cur == dir && IsRemoteNotFound(err) { + return nil, nil + } return nil, err } for _, entry := range entries { diff --git a/internal/sandbox/session_shell_snapshot_test.go b/internal/sandbox/session_shell_snapshot_test.go new file mode 100644 index 00000000..08c0ec50 --- /dev/null +++ b/internal/sandbox/session_shell_snapshot_test.go @@ -0,0 +1,210 @@ +package sandbox + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" +) + +type shellSnapshotClient struct { + *fakeRemoteClient + ops []string + handles []string + listCalls int + execCalls int + listErrorAt int + listErr error + prepError bool + command *RemoteExecResult + directories map[string][]RemoteDirEntry +} + +func (c *shellSnapshotClient) ConnectSession( + ctx context.Context, req RemoteConnectRequest, +) (RemoteSandboxHandle, error) { + c.ops = append(c.ops, "connect") + return c.Connect(ctx, req) +} + +func (c *shellSnapshotClient) Stat(context.Context, RemoteSandboxHandle, string) (*RemoteStatEntry, error) { + c.ops = append(c.ops, "stat") + return nil, errors.New("snapshot must not stat") +} + +func (c *shellSnapshotClient) ListDir( + ctx context.Context, handle RemoteSandboxHandle, dir string, +) ([]RemoteDirEntry, error) { + c.ops = append(c.ops, "list") + c.handles = append(c.handles, handle.ID()) + c.listCalls++ + if c.listCalls == c.listErrorAt { + return nil, c.listErr + } + if c.directories != nil { + return c.directories[dir], ctx.Err() + } + return []RemoteDirEntry{{Path: dir + "/report.txt", Type: RemoteEntryFile, Size: int64(c.listCalls)}}, ctx.Err() +} + +func (c *shellSnapshotClient) Exec( + ctx context.Context, handle RemoteSandboxHandle, req RemoteExecRequest, +) (*RemoteExecResult, error) { + c.ops = append(c.ops, "exec") + c.handles = append(c.handles, handle.ID()) + c.execCalls++ + if c.execCalls == 1 && c.prepError { + return &RemoteExecResult{ExitCode: 1, Stderr: "permission denied"}, nil + } + if c.execCalls == 2 && c.command != nil { + if req.OnOutput != nil { + req.OnOutput("stdout", []byte(c.command.Stdout)) + } + return c.command, nil + } + return c.fakeRemoteClient.Exec(ctx, handle, req) +} + +func newShellSnapshotHarness(t *testing.T) (context.Context, *SessionBoundManager, *shellSnapshotClient) { + t.Helper() + client := &shellSnapshotClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)} + cfg := DefaultConfig() + cfg.CubeTemplate = "tpl-test" + mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{ + Config: cfg, Client: client, Store: NewMemorySessionSandboxBindingStore(), + Checker: &fakeSessionExistenceChecker{exists: true}, SkipHealthProbe: true, + }) + require.NoError(t, err) + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000)) + _, err = mgr.resolveSession(ctx, "sess-1") + require.NoError(t, err) + return ctx, mgr, client +} + +func TestShellOutputSnapshotUsesOneHandleAndFiveOperations(t *testing.T) { + ctx, mgr, client := newShellSnapshotHarness(t) + client.command = &RemoteExecResult{Stdout: "hello", Stderr: "warning", ExitCode: 7, Duration: time.Millisecond} + var streamed string + result, snapshot, err := mgr.ExecShellCommandWithOutputSnapshot(ctx, "sess-1", "echo hello", ShellExecOptions{ + OnOutput: func(_ string, p []byte) { streamed += string(p) }, + }, SessionOutputRoot) + require.NoError(t, err) + require.Equal(t, []string{"connect", "list", "exec", "exec", "list"}, client.ops) + require.Empty(t, client.getIDs, "combined connector must not be preceded by Get") + require.Len(t, client.connectIDs, 1) + for _, id := range client.handles { + require.Equal(t, client.connectIDs[0], id) + } + require.Equal(t, "hello", streamed) + require.Equal(t, 7, result.ExitCode) + require.Equal(t, "warning", result.Stderr) + require.Equal(t, time.Millisecond, result.Duration) + require.NotNil(t, snapshot) + require.Equal(t, int64(1), snapshot.Before[0].Size) + require.Equal(t, int64(2), snapshot.After[0].Size) + + _, _, err = mgr.ExecShellCommandWithOutputSnapshot(ctx, "sess-1", "true", ShellExecOptions{}, SessionOutputRoot) + require.NoError(t, err) + require.Len(t, client.connectIDs, 2, "handles must not be cached across tool calls") +} + +func TestShellOutputSnapshotFailuresDoNotReplayCommand(t *testing.T) { + for _, tc := range []struct { + name string + failAt int + listErr error + wantLists int + wantResult bool + }{ + {"before unavailable", 1, errors.New("offline"), 1, false}, + {"after unavailable", 2, errors.New("offline"), 2, false}, + { + "missing root", 1, + NewRemoteError(SandboxTypeCube, "ListDir", RemoteErrorKindNotFound, "missing", nil), 2, true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, mgr, client := newShellSnapshotHarness(t) + client.listErrorAt, client.listErr = tc.failAt, tc.listErr + result, snapshot, err := mgr.ExecShellCommandWithOutputSnapshot( + ctx, "sess-1", "true", ShellExecOptions{}, SessionOutputRoot, + ) + require.NoError(t, err) + require.True(t, result.IsSuccess()) + require.Equal(t, tc.wantResult, snapshot != nil) + require.Equal(t, 2, client.execCalls, "one preparation and one command, never retried") + require.Equal(t, tc.wantLists, client.listCalls) + if snapshot != nil { + require.Empty(t, snapshot.Before) + require.Len(t, snapshot.After, 1) + } + }) + } +} + +func TestShellOutputSnapshotPreparationFailureDoesNotStartCommand(t *testing.T) { + ctx, mgr, client := newShellSnapshotHarness(t) + client.prepError = true + result, snapshot, err := mgr.ExecShellCommandWithOutputSnapshot( + ctx, "sess-1", "true", ShellExecOptions{}, SessionOutputRoot, + ) + require.ErrorContains(t, err, "Command was not started") + require.Nil(t, result) + require.Nil(t, snapshot) + require.Equal(t, 1, client.execCalls) +} + +func TestShellOutputSnapshotPreservesTimeout(t *testing.T) { + ctx, mgr, client := newShellSnapshotHarness(t) + client.command = &RemoteExecResult{Stdout: "partial", Killed: true} + result, snapshot, err := mgr.ExecShellCommandWithOutputSnapshot( + ctx, "sess-1", "sleep 10", ShellExecOptions{}, SessionOutputRoot, + ) + require.NoError(t, err) + require.True(t, result.Killed) + require.Equal(t, ErrTimeout.Error(), result.Error) + require.Equal(t, "partial", result.Stdout) + require.NotNil(t, snapshot) + require.Equal(t, 2, client.execCalls) +} + +func TestShellOutputSnapshotRecursesWithoutStat(t *testing.T) { + ctx, mgr, client := newShellSnapshotHarness(t) + client.directories = map[string][]RemoteDirEntry{ + "/workspace/artifacts": {{Name: "nested", Type: RemoteEntryDir}}, + "/workspace/artifacts/nested": {{Name: "report.txt", Type: RemoteEntryFile, Size: 10}}, + } + _, snapshot, err := mgr.ExecShellCommandWithOutputSnapshot( + ctx, "sess-1", "true", ShellExecOptions{}, "/workspace/artifacts", + ) + require.NoError(t, err) + require.NotNil(t, snapshot) + require.Len(t, snapshot.Before, 1) + require.Equal(t, "/workspace/artifacts/nested/report.txt", snapshot.Before[0].Path) + require.Equal(t, snapshot.Before, snapshot.After) + require.Equal(t, []string{"connect", "list", "list", "exec", "exec", "list", "list"}, client.ops) +} + +func TestShellOutputSnapshotRejectsPartialRecursiveListing(t *testing.T) { + ctx, mgr, client := newShellSnapshotHarness(t) + client.directories = map[string][]RemoteDirEntry{ + SessionOutputRoot: { + {Name: "old.txt", Type: RemoteEntryFile}, + {Name: "nested", Type: RemoteEntryDir}, + }, + } + client.listErrorAt = 2 + client.listErr = NewRemoteError(SandboxTypeCube, "ListDir", RemoteErrorKindNotFound, + "subdirectory disappeared", nil) + result, snapshot, err := mgr.ExecShellCommandWithOutputSnapshot( + ctx, "sess-1", "true", ShellExecOptions{}, SessionOutputRoot, + ) + require.NoError(t, err) + require.True(t, result.IsSuccess()) + require.Nil(t, snapshot, "a partial baseline must not label old files as new outputs") + require.Equal(t, 2, client.execCalls) + require.Equal(t, 2, client.listCalls) +}