feat(observability): add granular OpenTelemetry spans for sandbox startup and execution (#10758)

## Thinking Path

> - Paperclip coordinates AI agent work and records execution data.
> - The sandbox startup path and the host-to-sandbox execution path need
clearer OpenTelemetry spans.
> - The trace data now shows wait time, critical path data, and bounded
labels.
> - This pull request adds bounded spans and closed attribute helpers
for sandbox startup and execution.
> - The result is better trace data with low cardinality and no secret
leakage.

## Linked Issues or Issue Description

- No public GitHub issue exists for this branch.
- Related PR: #10536
- This PR extends the sandbox OpenTelemetry work with exec spans, root
timing, and bounded labels.

## What Changed

- Added a closed span-attribute contract for sandbox startup data.
- Added a bounded label helper for command and region values.
- Threaded the active step context into the execution path.
- Added a `sandbox.exec` span with true timestamps and bounded
attributes.
- Added skipped-step and root-span timing data with low-cardinality
context.
- Moved handshake sub-times and bridge batch data onto spans.

## Verification

- `pnpm --filter @paperclipai/adapter-utils run typecheck`
- `pnpm --filter @paperclipai/server run typecheck`
- `pnpm --filter @paperclipai/adapter-utils exec vitest run`
- `pnpm --filter @paperclipai/server exec vitest run
environment-execution-target`
- `git log --oneline
origin/master..origin/feat/sandbox-startup-otel-spans`
- `git diff origin/master...origin/feat/sandbox-startup-otel-spans
--stat`

## Risks

- Span attribute rules could still miss a future field if new code skips
the shared helper.
- Low-cardinality labels may hide some detail, but that is the intended
tradeoff.
- Tracing stays fail-open, so a missing tracer still hides data rather
than stopping work.

## Model Used

- OpenAI Codex, GPT-5, tool use enabled. The runtime did not expose the
context window size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

The current head still has one failing required check: `e2e`. The PR
stays unready for board handoff until that check passes.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-08-03 10:13:19 -07:00
1 parent bc5c392331
commit c09ea7112b
9 files changed
+1515 -151

No files matched your search

@@ -8,11 +8,56 @@ vi.mock("../services/environment-config.js", () => ({
resolveEnvironmentDriverConfigForRuntime: mockResolveEnvironmentDriverConfigForRuntime,
}));
import {
measureStartupStep,
SANDBOX_STARTUP_SPAN_ATTRS,
} from "@paperclipai/adapter-utils/acpx-engine/startup-timing";
import {
DEFAULT_SANDBOX_REMOTE_CWD,
resolveEnvironmentExecutionTarget,
} from "../services/environment-execution-target.js";
const A = SANDBOX_STARTUP_SPAN_ATTRS;
// A recording trace context that models the OTel parenting contract:
// `startSpan(name, options, context)` reads the parent from the explicit
// `context` token that `contextWithSpan` built. A test asserts the exact parent
// of each child span without an OTel package.
function createRecordingTrace() {
const spans: Array<{
name: string;
attributes: Record<string, unknown>;
parent: unknown;
ended: boolean;
setAttribute(key: string, value: unknown): void;
end(): void;
}> = [];
const tracer = {
startSpan(name: string, _options?: unknown, context?: unknown) {
const parent =
context && typeof context === "object" && "span" in context
? (context as { span: unknown }).span
: null;
const span = {
name,
attributes: {} as Record<string, unknown>,
parent,
ended: false,
setAttribute(key: string, value: unknown) {
span.attributes[key] = value;
},
end() {
span.ended = true;
},
};
spans.push(span);
return span;
},
};
const contextWithSpan = (span: unknown) => ({ span });
return { tracer, contextWithSpan, spans };
}
describe("resolveEnvironmentExecutionTarget", () => {
beforeEach(() => {
mockResolveEnvironmentDriverConfigForRuntime.mockReset();
@@ -424,16 +469,25 @@ describe("resolveEnvironmentExecutionTarget", () => {
// A recording tracer that captures each provider-exec span's name, attribute
// map, and end. It satisfies the structural tracer the seam calls.
function createRecordingExecTracer() {
const spans: Array<{ name: string; attributes: Record<string, unknown>; ended: boolean }> = [];
const spans: Array<{
name: string;
attributes: Record<string, unknown>;
status: { code: number; message?: string } | null;
ended: boolean;
}> = [];
const tracer = {
startSpan(name: string) {
const span = {
name,
attributes: {} as Record<string, unknown>,
status: null as { code: number; message?: string } | null,
ended: false,
setAttribute(key: string, value: unknown) {
span.attributes[key] = value;
},
setStatus(status: { code: number; message?: string }) {
span.status = status;
},
end() {
span.ended = true;
},
@@ -445,25 +499,50 @@ describe("resolveEnvironmentExecutionTarget", () => {
return { tracer, spans };
}
// The closed span-attribute allowlist for a provider-exec span (Phase 4).
const ALLOWED_EXEC_SPAN_ATTRIBUTE_KEYS = new Set([
"provider",
"exit",
"provider.exec.duration_ms",
"provider.get.duration_ms",
// The value of `SpanStatusCode.ERROR` in `@opentelemetry/api`. A failed exec
// span must carry this native status, not only the `failed` outcome attribute.
const SPAN_STATUS_CODE_ERROR = 2;
// The closed span-attribute allowlist for a `sandbox.exec` span. A test
// asserts every recorded key is in this set, so a command, an argument, a
// path, an id, or an error-text key can never ride the span.
const ALLOWED_EXEC_SPAN_ATTRIBUTE_KEYS = new Set<string>([
A.provider,
A.execCommand,
A.execExitCode,
A.execWallMs,
A.execWaitBeforeMs,
A.execSandboxMs,
A.execNetworkMs,
A.execCriticalPath,
A.outcome,
]);
async function runnerFor(input: {
provider: string;
execResult: Record<string, unknown>;
tracer: unknown;
}) {
return runnerWithExecute({
provider: input.provider,
tracer: input.tracer,
execute: vi.fn().mockResolvedValue(input.execResult),
});
}
// Build the sandbox runner with a custom provider-exec implementation, so a
// test can drive a thrown execution or assert the span order around the await.
async function runnerWithExecute(input: {
provider: string;
tracer: unknown;
execute: (...args: unknown[]) => Promise<unknown>;
}) {
mockResolveEnvironmentDriverConfigForRuntime.mockResolvedValue({
driver: "sandbox",
config: { provider: input.provider, reuseLease: false, timeoutMs: 30_000 },
});
const environmentRuntime = {
execute: vi.fn().mockResolvedValue(input.execResult),
execute: input.execute,
supportsSync: vi.fn().mockReturnValue(false),
};
const target = await resolveEnvironmentExecutionTarget({
@@ -501,12 +580,22 @@ describe("resolveEnvironmentExecutionTarget", () => {
expect(spans).toHaveLength(1);
const span = spans[0]!;
expect(span.name).toBe("provider.execute");
expect(span.name).toBe("sandbox.exec");
expect(span.ended).toBe(true);
expect(span.attributes["provider.exec.duration_ms"]).toBe(600);
expect(span.attributes["provider.get.duration_ms"]).toBe(15);
expect(span.attributes.provider).toBe("daytona");
expect(span.attributes.exit).toBe("ok");
// `sandbox_ms` = provider in-sandbox run; `wait_before_ms` = handle-fetch.
expect(span.attributes[A.execSandboxMs]).toBe(600);
expect(span.attributes[A.execWaitBeforeMs]).toBe(15);
expect(span.attributes[A.provider]).toBe("daytona");
// `echo` is a known command basename, so it rides as a clamped label.
expect(span.attributes[A.execCommand]).toBe("echo");
expect(span.attributes[A.execExitCode]).toBe(0);
expect(span.attributes[A.outcome]).toBe("ok");
// A successful exec leaves the native span status unset (default OTel status).
expect(span.status).toBeNull();
expect(span.attributes[A.execCriticalPath]).toBe(true);
// The wall time is a real, finite, non-negative number.
expect(typeof span.attributes[A.execWallMs]).toBe("number");
expect(span.attributes[A.execWallMs] as number).toBeGreaterThanOrEqual(0);
});
it("omits each duration attribute when a provider returns no timing (does not throw, keeps provider)", async () => {
@@ -521,10 +610,12 @@ describe("resolveEnvironmentExecutionTarget", () => {
expect(spans).toHaveLength(1);
const span = spans[0]!;
expect("provider.exec.duration_ms" in span.attributes).toBe(false);
expect("provider.get.duration_ms" in span.attributes).toBe(false);
expect(A.execSandboxMs in span.attributes).toBe(false);
expect(A.execWaitBeforeMs in span.attributes).toBe(false);
// With no provider durations, the derived network time is also omitted.
expect(A.execNetworkMs in span.attributes).toBe(false);
// The provider attribute is always present so a trace shows which provider ran.
expect(span.attributes.provider).toBe("kubernetes");
expect(span.attributes[A.provider]).toBe("kubernetes");
});
it("never emits a `0` duration attribute for a Daytona timeout that omits durationMs", async () => {
@@ -546,12 +637,18 @@ describe("resolveEnvironmentExecutionTarget", () => {
await runner.execute({ command: "sleep", args: ["999"] });
const span = spans[0]!;
expect("provider.exec.duration_ms" in span.attributes).toBe(false);
expect(span.attributes["provider.get.duration_ms"]).toBe(20);
expect(span.attributes.exit).toBe("error");
expect(A.execSandboxMs in span.attributes).toBe(false);
expect(span.attributes[A.execWaitBeforeMs]).toBe(20);
// A non-zero exit yields `failed`; the exit code rides as a number.
expect(span.attributes[A.outcome]).toBe("failed");
// A failed exec also sets the native span status to ERROR.
expect(span.status).toEqual({ code: SPAN_STATUS_CODE_ERROR });
expect(span.attributes[A.execExitCode]).toBe(124);
// `sleep` is not in the known-command allowlist, so it clamps to `other`.
expect(span.attributes[A.execCommand]).toBe("other");
});
it("never sets a command, arg, or non-allowlisted key as an indexed span attribute", async () => {
it("never sets a command, arg, env, cwd, or stream text as a span attribute, even with secret-like input", async () => {
const { tracer, spans } = createRecordingExecTracer();
const runner = await runnerFor({
provider: "daytona",
@@ -559,22 +656,48 @@ describe("resolveEnvironmentExecutionTarget", () => {
exitCode: 0,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
// Secret-like standard-stream text must never ride the span.
stdout: "AKIAIOSFODNN7EXAMPLE token=s3cr3t-stdout",
stderr: "error at /home/agent/.ssh/id_rsa: s3cr3t-stderr",
metadata: { durationMs: 5, getDurationMs: 1 },
},
tracer,
});
await runner.execute({ command: "bash -lc 'rm -rf /secret/path'", args: ["--token", "s3cr3t"] });
await runner.execute({
// A full command line, a secret-like argument, a secret-like env value, a
// stdin blob, and a path-like cwd — none may ride the span.
command: "bash -lc 'rm -rf /secret/path'",
args: ["--token", "s3cr3t-arg", "--password", "hunter2"],
env: { AWS_SECRET_ACCESS_KEY: "s3cr3t-env", HOME: "/home/agent" },
cwd: "/home/agent/secret-workspace/.git",
stdin: "s3cr3t-stdin-blob",
});
const span = spans[0]!;
for (const key of Object.keys(span.attributes)) {
expect(ALLOWED_EXEC_SPAN_ATTRIBUTE_KEYS.has(key), `non-allowlisted key "${key}"`).toBe(true);
}
// The command clamps to the bounded `other` fallback (not a known basename).
expect(span.attributes[A.execCommand]).toBe("other");
// No forbidden substring rides any attribute value.
const values = Object.values(span.attributes).map(String);
expect(values.some((value) => value.includes("rm -rf"))).toBe(false);
expect(values.some((value) => value.includes("s3cr3t"))).toBe(false);
for (const forbidden of [
"rm -rf",
"s3cr3t",
"hunter2",
"AKIA",
"id_rsa",
"/secret/path",
"/home/agent",
"secret-workspace",
"stdin",
]) {
expect(
values.some((value) => value.includes(forbidden)),
`attribute value leaked "${forbidden}"`,
).toBe(false);
}
});
it("normalizes a plugin-backed provider key to `plugin` and keeps a built-in family as-is", async () => {
@@ -585,7 +708,7 @@ describe("resolveEnvironmentExecutionTarget", () => {
tracer: plugin.tracer,
});
await pluginRunner.execute({ command: "echo" });
expect(plugin.spans[0]!.attributes.provider).toBe("plugin");
expect(plugin.spans[0]!.attributes[A.provider]).toBe("plugin");
const builtIn = createRecordingExecTracer();
const builtInRunner = await runnerFor({
@@ -594,6 +717,139 @@ describe("resolveEnvironmentExecutionTarget", () => {
tracer: builtIn.tracer,
});
await builtInRunner.execute({ command: "echo" });
expect(builtIn.spans[0]!.attributes.provider).toBe("e2b");
expect(builtIn.spans[0]!.attributes[A.provider]).toBe("e2b");
});
it("parents the exec span to the active step span when the exec runs inside a measured step", async () => {
const { tracer, contextWithSpan, spans } = createRecordingTrace();
const runner = await runnerFor({
provider: "daytona",
execResult: { exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "" },
tracer,
});
// The exec seam reads the active step context through `getActiveStepContext`.
// Wrap the exec in one measured step and assert the exec span parents to the
// step span, not to nothing.
await measureStartupStep({}, () => 0, "stage.sync", () => runner.execute({ command: "echo" }), {
tracer,
contextWithSpan,
});
const stepSpan = spans.find((span) => span.name === "stage.sync");
const execSpan = spans.find((span) => span.name === "sandbox.exec");
expect(stepSpan).toBeTruthy();
expect(execSpan).toBeTruthy();
expect(execSpan!.parent).toBe(stepSpan);
});
it("opens an unparented exec span when the exec runs outside any measured step", async () => {
const { tracer, spans } = createRecordingTrace();
const runner = await runnerFor({
provider: "daytona",
execResult: { exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "" },
tracer,
});
// No measured step wraps the exec, so the active step context is null and
// the exec span opens unparented (a no-op when tracing is off).
await runner.execute({ command: "echo" });
const execSpan = spans.find((span) => span.name === "sandbox.exec");
expect(execSpan).toBeTruthy();
expect(execSpan!.parent).toBeNull();
});
it("opens the exec span before the provider await so the span wraps the execution", async () => {
const { tracer, spans } = createRecordingExecTracer();
// Assert the span is already open (started, not ended) while the provider
// runs. If the seam opened the span after the await, no open span would
// exist here and the native span duration would be near zero.
const runner = await runnerWithExecute({
provider: "daytona",
tracer,
execute: vi.fn().mockImplementation(async () => {
const open = spans.find((span) => span.name === "sandbox.exec");
expect(open, "the exec span must be open during the provider await").toBeTruthy();
expect(open!.ended).toBe(false);
return { exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "" };
}),
});
await runner.execute({ command: "echo" });
const span = spans.find((s) => s.name === "sandbox.exec");
expect(span!.ended).toBe(true);
expect(span!.attributes[A.outcome]).toBe("ok");
});
it("records a failed exec span and rethrows when the provider execution throws", async () => {
const { tracer, spans } = createRecordingExecTracer();
const runner = await runnerWithExecute({
provider: "daytona",
tracer,
execute: vi.fn().mockRejectedValue(new Error("provider transport failed")),
});
// The original error rides through unchanged; observability never swallows it.
await expect(runner.execute({ command: "echo" })).rejects.toThrow("provider transport failed");
// A thrown execution still produces one ended span with the `failed` outcome,
// instead of no span at all.
const span = spans.find((s) => s.name === "sandbox.exec");
expect(span).toBeTruthy();
expect(span!.ended).toBe(true);
expect(span!.attributes[A.outcome]).toBe("failed");
// A thrown execution also sets the native span status to ERROR.
expect(span!.status).toEqual({ code: SPAN_STATUS_CODE_ERROR });
expect(span!.attributes[A.provider]).toBe("daytona");
// `echo` is a known basename, so the clamped command rides the span.
expect(span!.attributes[A.execCommand]).toBe("echo");
// No exec result exists, so the exit code never rides the span.
expect(A.execExitCode in span!.attributes).toBe(false);
// The wall time is a real, finite, non-negative number.
expect(typeof span!.attributes[A.execWallMs]).toBe("number");
expect(span!.attributes[A.execWallMs] as number).toBeGreaterThanOrEqual(0);
// Only allowlisted keys ride the failed span.
for (const key of Object.keys(span!.attributes)) {
expect(ALLOWED_EXEC_SPAN_ATTRIBUTE_KEYS.has(key), `non-allowlisted key "${key}"`).toBe(true);
}
});
it("keeps the exec span outcome `ok` when the execution succeeds but a log callback rejects", async () => {
const { tracer, spans } = createRecordingExecTracer();
// The provider execution succeeds and returns stdout, so the seam invokes
// the log callback. The callback rejects, which models a downstream log-sink
// failure. The rejection must reach the caller, but it must never reclassify
// the successful execution as a failed span.
const runner = await runnerWithExecute({
provider: "daytona",
tracer,
execute: vi.fn().mockResolvedValue({
exitCode: 0,
signal: null,
timedOut: false,
stdout: "hello",
stderr: "",
}),
});
const onLog = vi.fn().mockRejectedValue(new Error("log sink rejected"));
// The rejection rides through unchanged; observability never swallows it.
await expect(
(runner as { execute(input: unknown): Promise<unknown> }).execute({ command: "echo", onLog }),
).rejects.toThrow("log sink rejected");
// The span ended with the successful outcome from the command result, not
// the failed outcome. A log failure never marks the execution failed.
const span = spans.find((s) => s.name === "sandbox.exec");
expect(span).toBeTruthy();
expect(span!.ended).toBe(true);
expect(span!.attributes[A.outcome]).toBe("ok");
// A log-callback rejection never marks the span as ERROR; the status stays unset.
expect(span!.status).toBeNull();
expect(span!.attributes[A.execExitCode]).toBe(0);
// The seam reached the log callback exactly once (the stdout delivery).
expect(onLog).toHaveBeenCalledTimes(1);
});
});
+5
View File
@@ -43,6 +43,11 @@ interface StartupTracerHandle {
startSpan(
name: string,
options?: unknown,
// The optional explicit parent-context token. A real OTel
// `startSpan(name, options, context)` parents the new span to the span that
// `context` carries. The no-op tracer ignores it. The exec seam passes the
// active step context here, so an exec span parents to its step span.
context?: unknown,
): {
setAttribute(key: string, value: unknown): void;
setStatus(status: { code: number; message?: string }): void;
@@ -5,7 +5,13 @@ import {
adapterExecutionTargetToRemoteSpec,
type AdapterExecutionTarget,
} from "@paperclipai/adapter-utils/execution-target";
import { normalizeProviderFamily } from "@paperclipai/adapter-utils/acpx-engine/startup-timing";
import {
clampSpanLabel,
getActiveStepContext,
normalizeProviderFamily,
SANDBOX_STARTUP_OUTCOME,
SANDBOX_STARTUP_SPAN_ATTRS,
} from "@paperclipai/adapter-utils/acpx-engine/startup-timing";
import { parseObject } from "../adapters/utils.js";
import { getStartupTracer } from "../instrumentation.js";
import { resolveEnvironmentDriverConfigForRuntime } from "./environment-config.js";
@@ -17,12 +23,25 @@ export const DEFAULT_SANDBOX_REMOTE_CWD = "/tmp";
* span satisfies it; the no-op tracer's span satisfies it too. */
type ExecSpan = {
setAttribute(key: string, value: string | number | boolean): void;
setStatus(status: { code: number; message?: string }): void;
end(): void;
};
/**
* The value of `SpanStatusCode.ERROR` in `@opentelemetry/api`. The server injects
* a real OTel span, but this module stays OTel-free, so it uses the numeric value
* directly. A failed exec span sets this status, so a trace UI counts and filters
* the failure through the native span status, not only the `outcome` attribute.
*/
const SPAN_STATUS_CODE_ERROR = 2;
/** The minimal tracer surface the provider-exec seam calls. `getStartupTracer`
* returns a real or no-op implementation that satisfies it. */
type ExecTracer = { startSpan(name: string): ExecSpan };
* returns a real or no-op implementation that satisfies it. The optional third
* argument is the explicit parent-context token: the seam passes the active
* step context, so the exec span parents to its step span. */
type ExecTracer = {
startSpan(name: string, options?: unknown, context?: unknown): ExecSpan;
};
/**
* Set a numeric span attribute only when the value is a finite number. A value
@@ -36,6 +55,96 @@ function setFiniteNumberAttr(span: ExecSpan, key: string, value: unknown): void
}
}
/** Read a free-form metadata value as a finite number, or `undefined`. The
* provider durations ride the exec result's untyped `metadata`, so a provider
* that omits or mistypes one yields no attribute — never a misleading `0`. */
function toFiniteNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
/**
* The closed input for one `sandbox.exec` span. The seam builds it from the
* exec result and the active step context. Every field is already bounded or
* numeric; the raw command clamps inside the helper below.
*/
interface SandboxExecSpanInput {
/** The low-cardinality provider family (already through `normalizeProviderFamily`). */
provider: string;
/** The raw `argv[0]`. The helper clamps it; the raw value never rides the span. */
command: string;
/** The numeric process exit code, or `null`. */
exitCode: number | null;
/** The host-measured wall time of the execution. */
wallMs: number;
/** The provider handle-fetch wait before the execution ran. */
waitBeforeMs: number | undefined;
/** The in-sandbox run time of the execution. */
sandboxMs: number | undefined;
/** Whether the execution sits on the startup critical path. */
criticalPath: boolean;
}
/**
* Assemble every `sandbox.exec` span attribute in one place. This is the single
* producer-side boundary for the exec span: it sets only the closed
* `paperclip.sandbox.startup.exec.*` allowlist. The command rides only as a
* clamped label, so a full command line, an argument, a path, an environment
* value, or any standard-stream text can never ride the span. A non-finite
* numeric input yields no attribute (fail open — never `NaN`, never a
* misleading `0`).
*/
function setSandboxExecSpanAttributes(span: ExecSpan, input: SandboxExecSpanInput): void {
const A = SANDBOX_STARTUP_SPAN_ATTRS;
span.setAttribute(A.provider, input.provider);
const command = clampSpanLabel("command", input.command);
if (command !== undefined) span.setAttribute(A.execCommand, command);
if (typeof input.exitCode === "number" && Number.isFinite(input.exitCode)) {
span.setAttribute(A.execExitCode, input.exitCode);
}
setFiniteNumberAttr(span, A.execWallMs, input.wallMs);
setFiniteNumberAttr(span, A.execWaitBeforeMs, input.waitBeforeMs);
setFiniteNumberAttr(span, A.execSandboxMs, input.sandboxMs);
// The transport time the host adds around the provider work: wall minus the
// handle-fetch wait minus the in-sandbox run. Set it only when both parts are
// present, so a provider that reports no durations yields no derived value.
if (input.waitBeforeMs !== undefined && input.sandboxMs !== undefined) {
setFiniteNumberAttr(span, A.execNetworkMs, input.wallMs - input.waitBeforeMs - input.sandboxMs);
}
span.setAttribute(A.execCriticalPath, input.criticalPath);
const failed = input.exitCode !== 0;
span.setAttribute(
A.outcome,
failed ? SANDBOX_STARTUP_OUTCOME.failed : SANDBOX_STARTUP_OUTCOME.ok,
);
// A non-zero exit code is a failed execution, so set the native span status to
// ERROR too. The success path leaves the status unset, so a successful exec
// keeps the default OTel status. A `null` exit code counts as failed here.
if (failed) span.setStatus({ code: SPAN_STATUS_CODE_ERROR });
}
/**
* Record a failed `sandbox.exec` span when the provider execution throws. There
* is no exec result, so only the bounded provider family, the clamped command
* label, the measured wall time, the critical-path flag, and the `failed`
* outcome ride the span. The raw command never rides the span. A thrown
* execution now still produces a span, instead of no span at all.
*/
function setSandboxExecSpanFailure(
span: ExecSpan,
input: { provider: string; command: string; wallMs: number; criticalPath: boolean },
): void {
const A = SANDBOX_STARTUP_SPAN_ATTRS;
span.setAttribute(A.provider, input.provider);
const command = clampSpanLabel("command", input.command);
if (command !== undefined) span.setAttribute(A.execCommand, command);
setFiniteNumberAttr(span, A.execWallMs, input.wallMs);
span.setAttribute(A.execCriticalPath, input.criticalPath);
span.setAttribute(A.outcome, SANDBOX_STARTUP_OUTCOME.failed);
// A thrown execution is a failed execution, so set the native span status to
// ERROR too, not only the `outcome` attribute.
span.setStatus({ code: SPAN_STATUS_CODE_ERROR });
}
export async function resolveEnvironmentExecutionTarget(input: {
db: Db;
companyId: string;
@@ -141,49 +250,112 @@ export async function resolveEnvironmentExecutionTarget(input: {
providerGetMs: () => providerGetMs,
execute: async (commandInput) => {
execCount += 1;
const startedAt = new Date().toISOString();
const result = await input.environmentRuntime!.execute({
environment: input.environment as Environment,
lease: input.lease!,
command: commandInput.command,
args: commandInput.args,
cwd: commandInput.cwd ?? remoteCwd,
env: commandInput.env,
stdin: commandInput.stdin,
timeoutMs: commandInput.timeoutMs,
});
accumulateProviderDurations(result.metadata);
// Emit one span for this host→sandbox exec (opt-in; a no-op tracer
// when tracing is off). It carries ONLY closed-allowlist,
// low-cardinality attributes: the normalized provider family, the
// exit status (a two-value enum), and the host-received provider
// durations (per field, only when finite). The full command, args,
// env, stdout, and stderr never ride a span — not as an attribute
// and not as an event. The span name is the fixed operation label.
// Record true start and stop timestamps around the provider await,
// so the exec span and the result carry a real wall time.
const startedAtMs = Date.now();
const startedAt = new Date(startedAtMs).toISOString();
// Open one `sandbox.exec` span BEFORE the provider await, so the
// native span duration covers the whole execution and a thrown
// execution still produces a span. The span parents to the active
// step span. `startSpan` sits inside a guard; observability must
// never change execution control flow, and a no-op tracer
// (tracing off) makes the whole block inert.
const activeStep = getActiveStepContext();
const criticalPath = activeStep?.criticalPath ?? true;
let span: ExecSpan | null = null;
try {
const span = tracer.startSpan("provider.execute");
try {
span.setAttribute("provider", providerFamily);
span.setAttribute("exit", result.exitCode === 0 ? "ok" : "error");
setFiniteNumberAttr(span, "provider.exec.duration_ms", result.metadata?.durationMs);
setFiniteNumberAttr(span, "provider.get.duration_ms", result.metadata?.getDurationMs);
} finally {
span.end();
}
span = tracer.startSpan("sandbox.exec", undefined, activeStep?.parentContext);
} catch {
// Observability must not change execution control flow.
span = null;
}
try {
// Classify the span outcome from the provider execution ONLY.
// The inner try/catch wraps just the provider await, so a thrown
// provider execution marks the span failed. A later log-callback
// rejection sits outside this block and never flips a successful
// execution to failed.
let result;
try {
result = await input.environmentRuntime!.execute({
environment: input.environment as Environment,
lease: input.lease!,
command: commandInput.command,
args: commandInput.args,
cwd: commandInput.cwd ?? remoteCwd,
env: commandInput.env,
stdin: commandInput.stdin,
timeoutMs: commandInput.timeoutMs,
});
} catch (error) {
// The provider execution threw. Mark the span failed with the
// measured wall time, then rethrow the original error unchanged.
if (span) {
try {
setSandboxExecSpanFailure(span, {
provider: providerFamily,
command: commandInput.command,
wallMs: Date.now() - startedAtMs,
criticalPath,
});
} catch {
// Observability must not change execution control flow.
}
}
throw error;
}
// The provider execution succeeded. The span timing and outcome
// come from the command result, not from the log callbacks below.
const finishedAtMs = Date.now();
const finishedAt = new Date(finishedAtMs).toISOString();
const durationMs = finishedAtMs - startedAtMs;
accumulateProviderDurations(result.metadata);
// `setSandboxExecSpanAttributes` sets ONLY the closed
// `paperclip.sandbox.startup.exec.*` allowlist: the normalized
// provider family, the clamped command label, the numeric exit
// code, the wall / wait-before / sandbox / network times, the
// critical-path flag, and the outcome. The full command, args,
// env, stdout, and stderr never ride the span.
if (span) {
try {
setSandboxExecSpanAttributes(span, {
provider: providerFamily,
command: commandInput.command,
exitCode: result.exitCode,
wallMs: durationMs,
waitBeforeMs: toFiniteNumber(result.metadata?.getDurationMs),
sandboxMs: toFiniteNumber(result.metadata?.durationMs),
criticalPath,
});
} catch {
// Observability must not change execution control flow.
}
}
// Deliver the captured output. A rejected `onLog` still
// propagates to the caller (control flow is unchanged), but the
// span already carries the successful outcome, so a log failure
// never marks the execution failed.
if (result.stdout) await commandInput.onLog?.("stdout", result.stdout);
if (result.stderr) await commandInput.onLog?.("stderr", result.stderr);
return {
exitCode: result.exitCode,
signal: result.signal ?? null,
timedOut: result.timedOut,
stdout: result.stdout,
stderr: result.stderr,
pid: null,
startedAt,
finishedAt,
durationMs,
};
} finally {
if (span) {
try {
span.end();
} catch {
// Observability must not change execution control flow.
}
}
}
if (result.stdout) await commandInput.onLog?.("stdout", result.stdout);
if (result.stderr) await commandInput.onLog?.("stderr", result.stderr);
return {
exitCode: result.exitCode,
signal: result.signal ?? null,
timedOut: result.timedOut,
stdout: result.stdout,
stderr: result.stderr,
pid: null,
startedAt,
};
},
// Expose the native file-sync capability only when the provider's
// worker advertises BOTH sync verbs; otherwise leave syncIn/syncOut