The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
trace(server): time workspace, native setup and startup recovery (#16330)
Dottaebceb2a74465
diff --git a/doc/observability.md b/doc/observability.mdindex 36d2fc2554..568b1eb638 100644--- a/doc/observability.md+++ b/doc/observability.md@@ -175,7 +175,7 @@ GitHub identity selection, secret resolution, managed AI runtime preparation,skill inventory, connector assignments, connector skill preparation and delivery,connection instructions, and agent identity. Their names are`heartbeat.prepare.configuration_<step>`, using the closed names in-`server/src/services/heartbeat/preparation-timing.ts`. These intervals are inside+`server/src/services/execution-preparation-timing.ts`. These intervals are inside`execution_configuration`; do not add them to its duration. They remain availablewhen a later setup step fails before the provider lifecycle trace starts.@@ -194,6 +194,41 @@ traces; the provider lifecycle trace is created later and can have a differenttrace ID. Without an endpoint, tracing remains a no-op. These spans add nofirst-party Telemetry events or database run-log writes.+Workspace preparation also records `heartbeat.prepare.workspace_<step>` spans+for source resolution, provisioning policy, base validation, source access,+provisioning, retained source access, workspace record creation and updates,+task binding, operation binding, configuration records, repository admission,+project repositories, and recovery-root reservation. These intervals are inside+`heartbeat.prepare.workspace`. Repeated bindings or updates have separate spans.+Do not add these intervals to the containing workspace duration. They use the+same run hash and contain no workspace paths, commands, or returned records.++The `paperclip.native-controller` tracer records separate+`native.controller.<phase>` root spans around GitHub access setup, wake binding,+backend construction, connector assignments, assigned MCP discovery, tool+authority, companion selection and Runner binary resolution. It also records+GitHub shutdown, coordinator release, instruction checkpoints and collection,+and warm-session release. These intervals can occur between the existing native+preparation, execution and settlement spans. They are controller work, not model+turn time, and carry only the existing run hash. Nested phases overlap their+containing backend or lifecycle intervals; do not add both durations.++All preparation timing uses the endpoint gate, even when another library has+registered a tracer provider. Tracer lookup, callback, status or ending failures+cannot repeat work or replace its result or error. Automatic database children+are not guaranteed: an aggregate workspace trace can contain just one span.+If a process exits before an operation settles, its open span may not be exported.++With an endpoint, `paperclip.controller-startup` records independent+`controller.startup.<phase>` root spans for tool reviews, gateway sessions,+delivery-worker readiness, accounting, plugin-worker readiness, native recovery,+hot-restart adoption, orphan reaping, scheduled retries, queued runs, and goal+recovery. These spans have no custom attributes. Each ends when its awaited+phase settles, including failures. They separate controller readiness from+provider startup; they are not agent-run durations. A disabled endpoint takes+the direct work path without a tracer lookup or additional log messages.+Tracing failures cannot repeat recovery or replace its result or error.+## Native Runner Trace SpansPaperclip Runner task runs emit a single foldable OpenTelemetry trace. This isdiff --git a/maps/agent-access-map/runs-adapters.md b/maps/agent-access-map/runs-adapters.mdindex 7f8076b487..b219918ba4 100644--- a/maps/agent-access-map/runs-adapters.md+++ b/maps/agent-access-map/runs-adapters.md@@ -126,6 +126,15 @@ settings. See [creation access](./agents.md#hire).Review: `baseline`.+Scoped source-only timing evidence: workspace preparation spans carry only the+existing hashed run ID. Controller startup phase spans carry no custom attributes.+Native controller setup and settlement phases use that same run hash, including+assigned MCP discovery; neither tool definitions nor credentials are recorded.+Both retain operator-controlled tracing; unconfigured clients stay silent.+This adds no agent API, credential access, run-log write, or recovery authority.+See [the tracing contract](../../doc/observability.md#controller-preparation-phases).+Live latency verification remains separate from the existing access baseline.+API: `present` — representative operation IDs:- `GET /api/heartbeat-runs/{runId}`.diff --git a/maps/feature-map/runs-adapters.md b/maps/feature-map/runs-adapters.mdindex e8639edd24..adc306c23d 100644--- a/maps/feature-map/runs-adapters.md+++ b/maps/feature-map/runs-adapters.md@@ -27,6 +27,16 @@ Open an agent’s model/adapter configuration or the instance adapter settings pOpen an agent run at `/agents/:agentId/runs/:runId` from the agent or task activity.+For latency diagnosis with an operator OTLP endpoint, search the hashed run ID+without restricting the root span name. Compare workspace preparation with its+`workspace_<step>` intervals. Measure controller readiness separately through+`controller.startup.<phase>`. A recovery pause or deployment drain is not model+execution time. See the [tracing contract](../../doc/observability.md#controller-preparation-phases).+These source-level diagnostics do not establish a live response-time budget.+Inspect `native.controller.<phase>` for backend construction, assigned-tool+discovery and post-turn cleanup. Compare those intervals with the actual model+turn; do not count a nested discovery interval twice.+## Driving it with Playwright and the Paperclip CLIPreconditions: follow the [baseline](./README.md#before-driving-a-journey). Record adapter, model, account, native/legacy runtime, and environment. Capabilities vary; one harness result is not a matrix-wide qualification.diff --git a/server/src/__tests__/heartbeat-execution-configuration.test.ts b/server/src/__tests__/heartbeat-execution-configuration.test.tsindex 2bd11211a1..42da904353 100644--- a/server/src/__tests__/heartbeat-execution-configuration.test.ts+++ b/server/src/__tests__/heartbeat-execution-configuration.test.ts@@ -63,7 +63,7 @@ describePostgres("heartbeat execution configuration through adapter dispatch", (testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }),});}, 30_000);- afterEach(() => { vi.restoreAllMocks(); skillFailures.clear(); });+ afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); skillFailures.clear(); });afterAll(async () => {await heartbeat?.drainActiveRunExecutions();unregisterServerAdapter(adapterType);@@ -113,6 +113,7 @@ describePostgres("heartbeat execution configuration through adapter dispatch", (});it("delivers the selected credential in an isolated home and removes it after completion", async () => {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test");const f = await seed(true);let providerHome: string | undefined;inspect.set(f.agentId, async input => {@@ -156,6 +157,7 @@ describePostgres("heartbeat execution configuration through adapter dispatch", (});it("cleans acquired credentials and redacts diagnostics when later skill preparation fails", async () => {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test");const f = await seed(true);skillFailures.set(f.companyId, `Invalid fixture skill configuration: ${f.credential}`);const capturedFailure = vi.spyOn(sentry, "captureRunFailure").mockImplementation(() => undefined);diff --git a/server/src/index.ts b/server/src/index.tsindex d2c89452af..cb45243a1a 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -1,3 +1,4 @@+import { timeStartupRecovery } from "./startup-recovery-timing.js";import { skillSourceSyncService } from "./services/skill-source-sync.js";import { subscribeAllCompanyLiveEvents } from "./services/live-events.js";import { DELIVERY_QUEUES } from "./services/delivery-work-notifications.js";@@ -1347,9 +1348,9 @@ async function startServerWithDatabaseTeardown(}));};- await app.locals.toolGateway.sweepActionReviews().catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed"));- await app.locals.toolGateway.cleanupExpiredSessions().catch((err: unknown) => logger.error({ err }, "startup gateway token cleanup failed"));- await Promise.all([fastResponseWorker, ...deliveryWorkers].map(worker => worker.ready));+ await timeStartupRecovery("tool_reviews", () => app.locals.toolGateway.sweepActionReviews()).catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed"));+ await timeStartupRecovery("gateway_sessions", () => app.locals.toolGateway.cleanupExpiredSessions()).catch((err: unknown) => logger.error({ err }, "startup gateway token cleanup failed"));+ await timeStartupRecovery("delivery_workers", () => Promise.all([fastResponseWorker, ...deliveryWorkers].map(worker => worker.ready)));scheduleGitHubConnectionEventPoll();scheduleGitHubConnectionContinuitySweep();@@ -1480,7 +1481,7 @@ async function startServerWithDatabaseTeardown(},"worktree run-execution cutoff state",);- await accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed; pending receipts will retry"));+ await timeStartupRecovery("accounting", () => accountingHeartbeat.reconcileCostAccounting()).catch((err) => logger.error({ err }, "Cost accounting recovery failed; pending receipts will retry"));const heartbeatSchedulingSuppression = await heartbeat.resolveSchedulingSuppression();// Reap orphaned runs before timer ticks start so wakeups cannot coalesce@@ -1494,9 +1495,9 @@ async function startServerWithDatabaseTeardown(const startupHeartbeatRecovery = (async () => {// Legacy remote recovery releases sandbox leases. Wait for provider// workers before cleanup or retry admission, including unmanaged installs.- await app.locals.bundledPluginsStartup;+ await timeStartupRecovery("plugin_workers", () => app.locals.bundledPluginsStartup);try {- const nativeRecovery = await heartbeat.recoverNativeRunsAfterRestart();+ const nativeRecovery = await timeStartupRecovery("native_recovery", () => heartbeat.recoverNativeRunsAfterRestart());if (nativeRecovery.dispositions.length > 0) {logger.info({@@ -1521,7 +1522,7 @@ async function startServerWithDatabaseTeardown(throw err;}try {- const hotRestart = await heartbeat.reconcileHotRestartAdoption();+ const hotRestart = await timeStartupRecovery("hot_restart", () => heartbeat.reconcileHotRestartAdoption());if (hotRestart.mode === "reported") {logger.info(hotRestart,@@ -1537,7 +1538,7 @@ async function startServerWithDatabaseTeardown(for (let attempt = 1; attempt <= 2; attempt++) {try {- const result = await heartbeat.reapOrphanedRuns();+ const result = await timeStartupRecovery("orphan_reaping", () => heartbeat.reapOrphanedRuns());logger.info({ reaped: result.reaped, runIds: result.runIds },"startup reap of orphaned heartbeat runs complete",@@ -1555,9 +1556,9 @@ async function startServerWithDatabaseTeardown(}}- const promotion = await heartbeat.promoteDueScheduledRetries();- await heartbeat.resumeQueuedRuns();- const recoveredGoalActions = await heartbeat.recoverPendingSessionGoalActions();+ const promotion = await timeStartupRecovery("scheduled_retries", () => heartbeat.promoteDueScheduledRetries());+ await timeStartupRecovery("queued_runs", () => heartbeat.resumeQueuedRuns());+ const recoveredGoalActions = await timeStartupRecovery("goal_actions", () => heartbeat.recoverPendingSessionGoalActions());if (recoveredGoalActions.enqueued > 0 ||recoveredGoalActions.invalid > 0@@ -1567,7 +1568,7 @@ async function startServerWithDatabaseTeardown("startup session-goal action outbox recovery reconciled pending controls",);}- const recoveredGoals = await heartbeat.recoverActiveSessionGoals();+ const recoveredGoals = await timeStartupRecovery("active_goals", () => heartbeat.recoverActiveSessionGoals());if (recoveredGoals.enqueued > 0) {logger.warn(recoveredGoals,@@ -1859,7 +1860,7 @@ async function startServerWithDatabaseTeardown(// is still required. A failed acquire can leak a paid provider sandbox, so// this path retries the teardown at startup and on the interval, exactly as// the enabled path does.- await accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed; pending receipts will retry"));+ await timeStartupRecovery("accounting", () => accountingHeartbeat.reconcileCostAccounting()).catch((err) => logger.error({ err }, "Cost accounting recovery failed; pending receipts will retry"));await runEnvironmentLeaseCleanupSweep(0);startHeartbeatSchedulerInterval(() => {trackHeartbeatSchedulerWork(accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed")));diff --git a/server/src/services/execution-preparation-timing.test.ts b/server/src/services/execution-preparation-timing.test.tsnew file mode 100644index 0000000000..f6467f5b54--- /dev/null+++ b/server/src/services/execution-preparation-timing.test.ts@@ -0,0 +1,42 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { createRunPreparationTiming } from "./execution-preparation-timing.js";++const handles = vi.hoisted(() => ({ getTracer: vi.fn(), startActiveSpan: vi.fn() }));+vi.mock("@opentelemetry/api", () => ({+ ROOT_CONTEXT: "root", SpanStatusCode: { ERROR: 2 },+ trace: { getTracer: handles.getTracer, getActiveSpan: () => undefined },+}));+beforeEach(() => {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test");+ handles.getTracer.mockReturnValue({ startActiveSpan: handles.startActiveSpan });+});+afterEach(() => vi.unstubAllEnvs());++it.each(["lookup", "start", "after_callback", "missing_callback", "rejected", "end", "status"])("runs work once and preserves its result or error when tracing fails at %s", async failure => {+ const broken = () => { throw new Error("tracing failed"); };+ handles.getTracer.mockImplementation(failure === "lookup" ? broken : () => ({ startActiveSpan: handles.startActiveSpan }));+ handles.startActiveSpan.mockImplementation((_name, _options, _context, callback) => {+ if (failure === "start") throw new Error("tracer failed before callback");+ if (failure === "missing_callback") return undefined;+ if (failure === "rejected") return Promise.reject(new Error("tracer rejected"));+ const result = callback({ end: failure === "end" ? broken : vi.fn(), setStatus: failure === "status" ? broken : vi.fn() });+ if (failure === "after_callback") throw new Error("tracer failed after callback");+ return result;+ });+ const timing = createRunPreparationTiming("private-run", "native.controller");+ const result = {};+ const work = vi.fn(async () => result);+ await expect(timing("backend_setup", work)).resolves.toBe(result);+ expect(work).toHaveBeenCalledOnce();+ const error = new Error("original private failure");+ const failedWork = vi.fn(async () => { throw error; });+ await expect(timing("assigned_mcp", failedWork)).rejects.toBe(error);+ expect(failedWork).toHaveBeenCalledOnce();+});++it.each([undefined, "", " "])("does not consult tracing for endpoint %s", async endpoint => {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", endpoint);+ handles.getTracer.mockClear();+ await expect(createRunPreparationTiming("run", "native.controller")("backend_setup", () => 42)).resolves.toBe(42);+ expect(handles.getTracer).not.toHaveBeenCalled();+});diff --git a/server/src/services/execution-preparation-timing.ts b/server/src/services/execution-preparation-timing.tsnew file mode 100644index 0000000000..ace73f626b--- /dev/null+++ b/server/src/services/execution-preparation-timing.ts@@ -0,0 +1,63 @@+import { createHash } from "node:crypto";+import { isSpanContextValid, ROOT_CONTEXT, SpanStatusCode, trace } from "@opentelemetry/api";++type PreparationPhase = "environment_selection" | "execution_configuration" | "session"+ | "workspace" | "github_environment" | "github_launchers" | "run_output"+ | "workspace_validation" | "runtime_services" | "instructions" | "runtime_selection"+ | "configuration_mentions" | "configuration_github_identity" | "configuration_secrets"+ | "configuration_ai_runtime" | "configuration_skills" | "configuration_connector_assignments"+ | "configuration_connector_skills" | "configuration_connector_delivery"+ | "configuration_connection_instructions" | "configuration_agent_identity"+ | "workspace_source_resolution"+ | "workspace_provision_policy"+ | "workspace_base_validation"+ | "workspace_source_authorization"+ | "workspace_provision"+ | "workspace_source_retention"+ | "workspace_binding"+ | "workspace_record_update"+ | "workspace_record_create"+ | "workspace_operation_binding"+ | "workspace_config_recording"+ | "workspace_repository_admission"+ | "workspace_project_repositories"+ | "workspace_recovery_root"+ | "github_access" | "wake_binding" | "backend_setup" | "connector_assignments"+ | "assigned_mcp" | "tool_authority" | "companion_selection" | "runner_binary"+ | "github_stop" | "coordinator_release" | "instruction_checkpoint"+ | "instruction_changes" | "warm_release" | "instruction_collection";++export function createRunPreparationTiming(runId: string, scope: "heartbeat.prepare" | "native.controller" = "heartbeat.prepare") {+ let runIdHash: string | undefined;+ return <T>(phase: PreparationPhase, work: () => T | Promise<T>): Promise<T> => {+ let operation: Promise<T> | undefined;+ const run = (span?: { setStatus(status: { code: number }): void; end(): void }) => {+ operation ??= (async () => {+ try { return await work(); }+ catch (error) {+ try { span?.setStatus({ code: SpanStatusCode.ERROR }); } catch {}+ throw error;+ } finally {+ try { span?.end(); } catch {}+ }+ })();+ return operation;+ };+ if (!process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim()) return run();+ try {+ runIdHash ??= createHash("sha256").update(runId).digest("hex").slice(0, 12);+ const trigger = trace.getActiveSpan()?.spanContext();+ const traced = trace.getTracer(scope === "heartbeat.prepare" ? "paperclip.heartbeat-preparation" : "paperclip.native-controller").startActiveSpan(+ `${scope}.${phase}`,+ {+ attributes: { "paperclip.task.run.run_id": runIdHash },+ ...(trigger && isSpanContextValid(trigger) ? { links: [{ context: trigger }] } : {}),+ },+ ROOT_CONTEXT,+ span => run(span),+ );+ void Promise.resolve(traced).catch(() => undefined);+ } catch {}+ return operation ?? run();+ };+}diff --git a/server/src/services/heartbeat/preparation-timing-context.test.ts b/server/src/services/heartbeat/preparation-timing-context.test.tsindex 824bf85bbf..912f995d2b 100644--- a/server/src/services/heartbeat/preparation-timing-context.test.ts+++ b/server/src/services/heartbeat/preparation-timing-context.test.ts@@ -3,10 +3,33 @@ import { setImmediate } from "node:timers/promises";import { context, trace, TraceFlags } from "@opentelemetry/api";import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";import { AlwaysOffSampler, ParentBasedSampler, TracerProvider, InMemorySpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace";-import { expect, it, vi } from "vitest";+import { afterEach, beforeEach, expect, it, vi } from "vitest";import { createHeartbeatPreparationTiming } from "./preparation-timing.js";+import { createRunPreparationTiming } from "../execution-preparation-timing.js";-it.each([TraceFlags.NONE, TraceFlags.SAMPLED])("records background preparation independently of trigger flags %i and links back to it", async traceFlags => {+beforeEach(() => vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test"));+afterEach(() => vi.unstubAllEnvs());++it.each(["heartbeat.prepare", "native.controller"] as const)("keeps %s disabled without an endpoint when another library registers tracing", async scope => {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", undefined);+ const exporter = new InMemorySpanExporter();+ const provider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter })] });+ expect(trace.setGlobalTracerProvider(provider)).toBe(true);+ const lookup = vi.spyOn(trace, "getTracer");+ try {+ await expect(createRunPreparationTiming("unconfigured-run", scope)("workspace", () => 42)).resolves.toBe(42);+ expect(lookup).not.toHaveBeenCalled();+ await provider.forceFlush();+ expect(exporter.getFinishedSpans()).toEqual([]);+ } finally {+ lookup.mockRestore();+ trace.disable();+ await provider.shutdown();+ }+});++it.each([["heartbeat.prepare", TraceFlags.NONE], ["heartbeat.prepare", TraceFlags.SAMPLED], ["native.controller", TraceFlags.NONE], ["native.controller", TraceFlags.SAMPLED]] as const)("records %s independently of trigger flags %i and links back to it", async (scope, traceFlags) => {+ const phaseName = scope === "heartbeat.prepare" ? "workspace" : "backend_setup";const manager = new AsyncLocalStorageContextManager().enable();const exporter = new InMemorySpanExporter();const provider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter })] });@@ -21,7 +44,7 @@ it.each([TraceFlags.NONE, TraceFlags.SAMPLED])("records background preparation itry {const result = {};await context.with(trace.setSpanContext(context.active(), trigger), async () => {- await expect(createHeartbeatPreparationTiming("background-run")("workspace", async () => {+ await expect(createRunPreparationTiming("background-run", scope)(phaseName, async () => {await setImmediate();const child = trace.getTracer("preparation-context-test").startSpan("background.child");expect(child.isRecording()).toBe(true);@@ -33,7 +56,7 @@ it.each([TraceFlags.NONE, TraceFlags.SAMPLED])("records background preparation iawait provider.forceFlush();const spans = exporter.getFinishedSpans();expect(spans).toHaveLength(2);- const phase = spans.find(span => span.name === "heartbeat.prepare.workspace")!;+ const phase = spans.find(span => span.name === `${scope}.${phaseName}`)!;const child = spans.find(span => span.name === "background.child")!;expect(phase.parentSpanContext).toBeUndefined();expect(phase.links).toHaveLength(1);@@ -77,7 +100,8 @@ it("honors an operator sampler that disables root traces even when the trigger i}});-it.each(["workspace", "configuration_ai_runtime", "configuration_skills", "configuration_agent_identity"] as const)("stays silent and preserves values and errors without a tracer provider for %s", async phase => {+it.each(["workspace", "configuration_ai_runtime", "configuration_skills", "configuration_agent_identity", "workspace_source_resolution", "workspace_provision_policy", "workspace_base_validation", "workspace_source_authorization", "workspace_provision", "workspace_source_retention", "workspace_binding", "workspace_record_update", "workspace_record_create", "workspace_operation_binding", "workspace_config_recording", "workspace_repository_admission", "workspace_project_repositories", "workspace_recovery_root", "backend_setup", "assigned_mcp", "github_access", "wake_binding", "connector_assignments", "tool_authority", "companion_selection", "runner_binary", "github_stop", "coordinator_release", "instruction_checkpoint", "instruction_changes", "warm_release", "instruction_collection"] as const)("stays silent and preserves values and errors without a tracer provider for %s", async phase => {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", undefined);trace.disable();context.disable();const messages = ["log", "info", "warn", "error", "debug"] as const;diff --git a/server/src/services/heartbeat/preparation-timing.test.ts b/server/src/services/heartbeat/preparation-timing.test.tsindex 270f62dfb0..2399d6ff7e 100644--- a/server/src/services/heartbeat/preparation-timing.test.ts+++ b/server/src/services/heartbeat/preparation-timing.test.ts@@ -1,5 +1,5 @@import { createHash } from "node:crypto";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { createHeartbeatPreparationTiming } from "./preparation-timing.js";const handles = vi.hoisted(() => ({ spans: [] as Array<{ setStatus: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn> }> }));@@ -15,7 +15,8 @@ vi.mock("@opentelemetry/api", () => ({}));describe("heartbeat preparation timing", () => {- beforeEach(() => { vi.clearAllMocks(); handles.spans.length = 0; });+ beforeEach(() => { vi.clearAllMocks(); handles.spans.length = 0; vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test"); });+ afterEach(() => vi.unstubAllEnvs());it("correlates preparation with the existing run hash without recording content", async () => {const runId = "private-run-id";diff --git a/server/src/services/heartbeat/preparation-timing.ts b/server/src/services/heartbeat/preparation-timing.tsindex 7cdad97b68..4a700dcd27 100644--- a/server/src/services/heartbeat/preparation-timing.ts+++ b/server/src/services/heartbeat/preparation-timing.ts@@ -1,35 +1 @@-import { createHash } from "node:crypto";-import { isSpanContextValid, ROOT_CONTEXT, SpanStatusCode, trace } from "@opentelemetry/api";--type PreparationPhase = "environment_selection" | "execution_configuration" | "session"- | "workspace" | "github_environment" | "github_launchers" | "run_output"- | "workspace_validation" | "runtime_services" | "instructions" | "runtime_selection"- | "configuration_mentions" | "configuration_github_identity" | "configuration_secrets"- | "configuration_ai_runtime" | "configuration_skills" | "configuration_connector_assignments"- | "configuration_connector_skills" | "configuration_connector_delivery"- | "configuration_connection_instructions" | "configuration_agent_identity";--export function createHeartbeatPreparationTiming(runId: string) {- const runIdHash = createHash("sha256").update(runId).digest("hex").slice(0, 12);- return <T>(phase: PreparationPhase, work: () => Promise<T>): Promise<T> => {- const trigger = trace.getActiveSpan()?.spanContext();- return trace.getTracer("paperclip.heartbeat-preparation").startActiveSpan(- `heartbeat.prepare.${phase}`,- {- attributes: { "paperclip.task.run.run_id": runIdHash },- ...(trigger && isSpanContextValid(trigger) ? { links: [{ context: trigger }] } : {}),- },- ROOT_CONTEXT,- async (span) => {- try {- return await work();- } catch (error) {- span.setStatus({ code: SpanStatusCode.ERROR });- throw error;- } finally {- span.end();- }- },- );- };-}+export { createRunPreparationTiming as createHeartbeatPreparationTiming } from "../execution-preparation-timing.js";diff --git a/server/src/services/heartbeat/workspace-preparation.test.ts b/server/src/services/heartbeat/workspace-preparation.test.tsindex f6d1eb827d..c704a7d75f 100644--- a/server/src/services/heartbeat/workspace-preparation.test.ts+++ b/server/src/services/heartbeat/workspace-preparation.test.ts@@ -23,6 +23,8 @@ import * as managedRepositoryCheckout from "../managed-repository-checkout.js";import { isolatedRemoteSourcePath } from "../isolated-remote-workspace-source.js";import { cleanupExecutionWorkspaceArtifacts } from "../workspace-runtime.js";import { issueService } from "../issues.js";+import { trace } from "@opentelemetry/api";+import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";const execFile = promisify(execFileCallback);const support = await getEmbeddedPostgresTestSupport();@@ -120,6 +122,47 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",expect(input.controllerLease.assertOwned).toHaveBeenCalledTimes(2);});+ it("records workspace steps around real persistence before environment acquisition", async () => {+ const { input, source, issue, envOrchestrator } = await fixture();+ const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test");+ const exporter = new InMemorySpanExporter();+ const provider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter })] });+ expect(trace.setGlobalTracerProvider(provider)).toBe(true);+ const acquire = envOrchestrator.acquireForRun;+ vi.spyOn(envOrchestrator, "acquireForRun").mockImplementation(async args => {+ const names = exporter.getFinishedSpans().map(span => span.name);+ expect(names).toContain("heartbeat.prepare.workspace_record_create");+ expect(names).toContain("heartbeat.prepare.workspace_binding");+ expect((await readIssue(issue.id)).executionWorkspaceId).toBe(args.persistedExecutionWorkspace?.id);+ return acquire(args);+ });+ try {+ const result = await prepareHeartbeatWorkspace(db, input);+ expect(result.executionWorkspace.cwd).toBe(source);+ await provider.forceFlush();+ const spans = exporter.getFinishedSpans();+ expect(spans.map(span => span.name)).toEqual(expect.arrayContaining([+ "heartbeat.prepare.workspace_source_resolution",+ "heartbeat.prepare.workspace_provision_policy",+ "heartbeat.prepare.workspace_base_validation",+ "heartbeat.prepare.workspace_provision",+ "heartbeat.prepare.workspace_operation_binding",+ "heartbeat.prepare.workspace_config_recording",+ "heartbeat.prepare.workspace_repository_admission",+ "heartbeat.prepare.workspace_project_repositories",+ ]));+ for (const span of spans) {+ expect(Object.keys(span.attributes)).toEqual(["paperclip.task.run.run_id"]);+ expect(JSON.stringify(span.attributes)).not.toContain(source);+ }+ } finally {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", endpoint);+ trace.disable();+ await provider.shutdown();+ }+ });+it.each(["create", "failed-save", "shared-retry-after-failed-save", "literal-branch", "legacy-explicit-source", "inherited-source", "legacy-untyped-source", "changed-source-intent", "context-source"] as const)("preserves restricted source isolation during %s", async scenario => {const { input, source, issue: originalIssue } = await fixture(true);await db.update(companies).set({ issueCounter: 1 }).where(eq(companies.id, originalIssue.companyId));diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.tsindex 0dfc5a4508..5969afb6ff 100644--- a/server/src/services/heartbeat/workspace-preparation.ts+++ b/server/src/services/heartbeat/workspace-preparation.ts@@ -1,3 +1,4 @@+import { createHeartbeatPreparationTiming } from "./preparation-timing.js";import {resolveWorkspaceAfterLowTrustPreflight,WorkspaceValidationFailure,@@ -149,6 +150,7 @@ function readNonEmptyString(value: unknown): string | null {export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacePreparationInput) {const { run, agent, controllerLease, nativeRunnerPreparationSpans } = input;+ const timeWorkspace = createHeartbeatPreparationTiming(run.id);const {issueRef,issueId,@@ -197,7 +199,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacconst {selectedEnvironmentDriver: lowTrustPreflightEnvironmentDriver,workspace: resolvedWorkspace,- } = await resolveWorkspaceAfterLowTrustPreflight({+ } = await timeWorkspace("workspace_source_resolution", () => resolveWorkspaceAfterLowTrustPreflight({db,trustPreset,isolatedWorkspacesEnabled: runtimeWorkspaceSelectionEnabled,@@ -328,15 +330,15 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac}: workspace;},- });+ }));const hostProvisionDriver = selectedEnvironmentForConfig?.driver ?? lowTrustPreflightEnvironmentDriver;- const copyOnlyProvisioning = await workspaceRequiresCopyOnlyProvisioning(db, {+ const copyOnlyProvisioning = await timeWorkspace("workspace_provision_policy", () => workspaceRequiresCopyOnlyProvisioning(db, {companyId: agent.companyId,task: issueRef ? { ...issueRef, workspaceSelection: input.task.workspaceSelection } : null,sourceProjectId: resolvedWorkspace.projectId,sourceWorkspaceId: resolvedWorkspace.workspaceId,boundWorkspace: reusableExistingExecutionWorkspace ?? existingExecutionWorkspace,- });+ }));const skipHostProvision = copyOnlyProvisioning || hostProvisionDriver === "sandbox" || hostProvisionDriver === "ssh";const hostExecutionWorkspaceConfig = isDotRun ? {} :stripHostWorkspaceProvision({@@ -352,7 +354,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacrepoRef: resolvedWorkspace.repoRef,additionalWorkspaces: resolvedWorkspace.additionalWorkspaces,} satisfies ExecutionWorkspaceInput;- await assertGitWorktreeBaseWorkspaceReady({+ await timeWorkspace("workspace_base_validation", () => assertGitWorktreeBaseWorkspaceReady({requestedExecutionWorkspaceMode,config: hostExecutionWorkspaceConfig,issue: issueRef,@@ -362,7 +364,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacmaterializationFailures: resolvedWorkspace.materializationFailures,localPathOnlyWorkspace: resolvedWorkspace.localPathOnlyWorkspace,},- });+ }));const workspaceStrategyForFingerprint = parseObject(hostExecutionWorkspaceConfig.workspaceStrategy,);@@ -491,9 +493,9 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac&& (latestWorkspaceStrategyType === "git_worktree"|| (workspaceReuseProvisioningPolicy.shouldRestoreExistingWorkspace && reusableExistingExecutionWorkspace?.strategyType === "git_worktree"))) {try {- isolatedWorkspaceSourceAccess = await assertIsolatedWorkspaceSourceReadAccess(db, {+ isolatedWorkspaceSourceAccess = await timeWorkspace("workspace_source_authorization", () => assertIsolatedWorkspaceSourceReadAccess(db, {companyId: agent.companyId, sourceCwd: executionWorkspaceBase.baseCwd, actor: isolatedWorkspaceSourceActor,- });+ }));} catch (error) {const [sourceChoice] = await db.select({ projectWorkspaceId: issues.projectWorkspaceId,executionWorkspaceId: issues.executionWorkspaceId,@@ -512,9 +514,9 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacresolvedWorkspace.cwd = cwd;isolatedRemoteSource = { schema: "paperclip.isolated-remote-source.v1", companyId: agent.companyId,issueId, repoUrl: executionWorkspaceBase.repoUrl };- isolatedWorkspaceSourceAccess = await assertIsolatedWorkspaceSourceReadAccess(db, {+ isolatedWorkspaceSourceAccess = await timeWorkspace("workspace_source_authorization", () => assertIsolatedWorkspaceSourceReadAccess(db, {companyId: agent.companyId, sourceCwd: cwd, actor: isolatedWorkspaceSourceActor,- });+ }));}}const beforeIsolatedSourceCopy = isolatedWorkspaceSourceAccess@@ -533,7 +535,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacexecutionWorkspace,reusedExecutionWorkspace,policy: resolvedWorkspaceReusePolicy,- } = isDotRun ? { executionWorkspace: { ...executionWorkspaceBase, strategy: "project_primary" as const, cwd: resolvedWorkspace.cwd, branchName: null, worktreePath: null, warnings: [], created: false, branchCreatedByRuntime: false } as RealizedExecutionWorkspace, reusedExecutionWorkspace: false, policy: workspaceReuseProvisioningPolicy } : await provisionExecutionWorkspaceForFreshnessDecision<RealizedExecutionWorkspace>(+ } = isDotRun ? { executionWorkspace: { ...executionWorkspaceBase, strategy: "project_primary" as const, cwd: resolvedWorkspace.cwd, branchName: null, worktreePath: null, warnings: [], created: false, branchCreatedByRuntime: false } as RealizedExecutionWorkspace, reusedExecutionWorkspace: false, policy: workspaceReuseProvisioningPolicy } : await timeWorkspace("workspace_provision", () => provisionExecutionWorkspaceForFreshnessDecision<RealizedExecutionWorkspace>({requestedShouldReuseExisting,existingExecutionWorkspaceId:@@ -636,9 +638,9 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacafterSourceCopy: afterIsolatedSourceCopy,}),},- );+ ));if (isolatedWorkspaceSourceAccess && executionWorkspace.strategy === "git_worktree") {- await retainIsolatedWorkspaceSourceAccess(db, {+ await timeWorkspace("workspace_source_retention", () => retainIsolatedWorkspaceSourceAccess(db, {companyId: agent.companyId,sourceCwd: executionWorkspaceBase.baseCwd,targetCwd: executionWorkspace.cwd,@@ -646,7 +648,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspaccaptured: isolatedWorkspaceSourceAccess,issueId: issueId ?? undefined,phase: "verified",- });+ }));}const resolvedProjectId =reusableExistingExecutionWorkspace@@ -709,7 +711,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac};}if (Object.keys(nextIssuePatch).length > 0) {- await executionWorkspacesSvc.bindTaskWorkspace(agent.companyId, issueId, workspace.id, nextIssuePatch);+ await timeWorkspace("workspace_binding", () => executionWorkspacesSvc.bindTaskWorkspace(agent.companyId, issueId, workspace.id, nextIssuePatch));issueExecutionWorkspaceIdForRun = workspace.id;issueProjectWorkspaceIdForRun =resolvedProjectWorkspaceId ?? issueProjectWorkspaceIdForRun;@@ -796,7 +798,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacpersistedExecutionWorkspace =resolvedWorkspaceReusePolicy.shouldRestoreExistingWorkspace &&reusableExistingExecutionWorkspace- ? await executionWorkspacesSvc.update(+ ? await timeWorkspace("workspace_record_update", () => executionWorkspacesSvc.update(reusableExistingExecutionWorkspace.id,{cwd: executionWorkspace.cwd,@@ -817,9 +819,9 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacresolvedProjectWorkspaceId,),},- )+ )): !isDotRun && !persistedNativeExecutionInput && (resolvedProjectId || issueRef)- ? await executionWorkspacesSvc.create({+ ? await timeWorkspace("workspace_record_create", () => executionWorkspacesSvc.create({companyId: agent.companyId,projectId: resolvedProjectId,projectWorkspaceId: resolvedProjectWorkspaceId,@@ -853,7 +855,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspaclastUsedAt: new Date(),openedAt: new Date(),metadata: nextExecutionWorkspaceMetadata,- })+ })): null;} catch (error) {if (executionWorkspace.created) {@@ -908,10 +910,10 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac}throw error;}- await workspaceOperationRecorder.attachExecutionWorkspaceId(+ await timeWorkspace("workspace_operation_binding", () => workspaceOperationRecorder.attachExecutionWorkspaceId(persistedExecutionWorkspace?.id ?? null,- );- await recordWorkspaceConfigFreshnessOperation({+ ));+ await timeWorkspace("workspace_config_recording", () => recordWorkspaceConfigFreshnessOperation({recorder: workspaceOperationRecorder,runId: run.id,decision: workspaceConfigFreshness,@@ -923,7 +925,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacpreviousWorkspaceId:workspaceReuseRequest.requestedExecutionWorkspaceId,activeWorkspaceId: persistedExecutionWorkspace?.id ?? null,- });+ }));if (reusableExistingExecutionWorkspace &&persistedExecutionWorkspace &&@@ -931,20 +933,20 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacpersistedExecutionWorkspace.id &&reusableExistingExecutionWorkspace.status === "active") {- await executionWorkspacesSvc.update(+ await timeWorkspace("workspace_record_update", () => executionWorkspacesSvc.update(reusableExistingExecutionWorkspace.id,{status: "idle",cleanupReason: null,},- );+ ));}await bindIssueToPersistedExecutionWorkspace(persistedExecutionWorkspace);const projectRepositoryPaths: string[] = [];if (persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) {- const taskRepositories = await executionWorkspacesSvc.prepareTaskRepositoriesForAdmission({ companyId: agent.companyId,- issueId, workspaceId: persistedExecutionWorkspace.id, cwd: executionWorkspace.cwd,- agentId: agent.id, runId: run.id, responsibleUserId });+ const taskRepositories = await timeWorkspace("workspace_repository_admission", () => executionWorkspacesSvc.prepareTaskRepositoriesForAdmission({ companyId: agent.companyId,+ issueId, workspaceId: persistedExecutionWorkspace!.id, cwd: executionWorkspace.cwd,+ agentId: agent.id, runId: run.id, responsibleUserId }));projectRepositoryPaths.push(...taskRepositories.map(repository => repository.relativePath));}if (executionWorkspace.projectId@@ -954,7 +956,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspaceq(projectWorkspaces.companyId, agent.companyId),eq(projectWorkspaces.projectId, executionWorkspace.projectId),)).orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id));- const repositories = await prepareProjectRepositoryWorkspaces({+ const repositories = await timeWorkspace("workspace_project_repositories", () => prepareProjectRepositoryWorkspaces({cwd: executionWorkspace.cwd,anchorRepoUrl: executionWorkspace.repoUrl,workspaces: repositoryRows,@@ -969,7 +971,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspaccompanyId: agent.companyId, issueId, workspaceId: persistedExecutionWorkspace!.id,cwd: executionWorkspace.cwd, agentId: agent.id, runId: run.id,}) : undefined,- });+ }));const paths = new Map(repositories.map((repo) => [repo.workspaceId, repo.cwd]));projectRepositoryPaths.push(...repositories.map((repo) => path.relative(executionWorkspace.cwd, repo.cwd)));if (resolvedWorkspace.workspaceId) paths.set(resolvedWorkspace.workspaceId, executionWorkspace.cwd);@@ -1155,8 +1157,8 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac&& executionTarget?.kind !== "remote"? persistedNativeExecutionInput.workspace.cwd: executionWorkspace.cwd;- await executionWorkspacesSvc.reserveTaskRepositoryRootForRecovery({ companyId: agent.companyId,- issueId, workspaceId, cwd, agentId: agent.id, runId: run.id });+ await timeWorkspace("workspace_recovery_root", () => executionWorkspacesSvc.reserveTaskRepositoryRootForRecovery({ companyId: agent.companyId,+ issueId, workspaceId, cwd, agentId: agent.id, runId: run.id }));}// Preserve the host-owned source before adapter context can share lease// metadata. A later copy-back failure must not adopt a rebound source.diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.tsindex 47cd86bc03..741bda8685 100644--- a/server/src/services/native-runtime/native-session-executor.test.ts+++ b/server/src/services/native-runtime/native-session-executor.test.ts@@ -1,3 +1,5 @@+import { trace } from "@opentelemetry/api";+import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";import { configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { readFileSync } from "node:fs";@@ -10060,33 +10062,54 @@ describe("runnerd provider runtime wiring", () => {});it("keeps assigned MCP credentials on the control plane for remote Codex", async () => {- const assignedMcpTools = { definitions: () => [], has: () => false, execute: vi.fn() };- state.createAssignedMcpTools.mockResolvedValueOnce(assignedMcpTools);- state.createBackend.mockClear();- state.createTransport.mockClear();- state.toolAuthorityDefinitions.mockClear();- await createRunnerdBackend({- db: leaseDb(execution), execution, runnerInstanceId: "runner-assigned-mcp",- runnerEnvironment: {- PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned",- PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3217/mcp/gateways/assigned-test",- PAPERCLIP_NATIVE_MCP_TOKEN: "private-run-token",- },- runnerExecutionTarget: {- kind: "remote", transport: "sandbox", providerKey: "daytona",- leaseId: "lease-assigned-mcp", remoteCwd: "/home/daytona/paperclip-workspace",- runner: { execute: vi.fn() },- } as never,- });- expect(state.createAssignedMcpTools).toHaveBeenCalledWith(expect.objectContaining({- gatewayPublicId: "assigned-test", bearerToken: "private-run-token",- }));- expect(state.toolAuthorityDefinitions).toHaveBeenCalledWith(expect.objectContaining({ assignedMcpTools }));- state.createBackend.mock.calls[0]![1].codexTransportFactory!();- const options = state.createTransport.mock.calls[0]![0] as { environment: NodeJS.ProcessEnv };- expect(options.environment.PAPERCLIP_NATIVE_MCP_NAME).toBeUndefined();- expect(options.environment.PAPERCLIP_NATIVE_MCP_URL).toBeUndefined();- expect(options.environment.PAPERCLIP_NATIVE_MCP_TOKEN).toBeUndefined();+ const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test");+ const exporter = new InMemorySpanExporter();+ const provider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter })] });+ expect(trace.setGlobalTracerProvider(provider)).toBe(true);+ try {+ const assignedMcpTools = { definitions: () => [], has: () => false, execute: vi.fn() };+ state.createAssignedMcpTools.mockResolvedValueOnce(assignedMcpTools);+ state.createBackend.mockClear();+ state.createTransport.mockClear();+ state.toolAuthorityDefinitions.mockClear();+ await createRunnerdBackend({+ db: leaseDb(execution), execution, runnerInstanceId: "runner-assigned-mcp",+ runnerEnvironment: {+ PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned",+ PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3217/mcp/gateways/assigned-test",+ PAPERCLIP_NATIVE_MCP_TOKEN: "private-run-token",+ },+ runnerExecutionTarget: {+ kind: "remote", transport: "sandbox", providerKey: "daytona",+ leaseId: "lease-assigned-mcp", remoteCwd: "/home/daytona/paperclip-workspace",+ runner: { execute: vi.fn() },+ } as never,+ });+ expect(state.createAssignedMcpTools).toHaveBeenCalledWith(expect.objectContaining({+ gatewayPublicId: "assigned-test", bearerToken: "private-run-token",+ }));+ expect(state.toolAuthorityDefinitions).toHaveBeenCalledWith(expect.objectContaining({ assignedMcpTools }));+ state.createBackend.mock.calls[0]![1].codexTransportFactory!();+ const options = state.createTransport.mock.calls[0]![0] as { environment: NodeJS.ProcessEnv };+ expect(options.environment.PAPERCLIP_NATIVE_MCP_NAME).toBeUndefined();+ expect(options.environment.PAPERCLIP_NATIVE_MCP_URL).toBeUndefined();+ expect(options.environment.PAPERCLIP_NATIVE_MCP_TOKEN).toBeUndefined();+ await provider.forceFlush();+ const spans = exporter.getFinishedSpans();+ expect(spans.map(span => span.name)).toEqual(expect.arrayContaining([+ "native.controller.assigned_mcp", "native.controller.tool_authority",+ "native.controller.wake_binding", "native.controller.companion_selection",+ ]));+ for (const span of spans) {+ expect(Object.keys(span.attributes)).toEqual(["paperclip.task.run.run_id"]);+ expect(JSON.stringify(span.attributes)).not.toContain("private-run-token");+ }+ } finally {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", endpoint);+ trace.disable();+ await provider.shutdown();+ }});it("makes remote authority archival idempotent and returns the archived state", async () => {diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.tsindex d1da1cd7b1..80e0f40add 100644--- a/server/src/services/native-runtime/native-session-executor.ts+++ b/server/src/services/native-runtime/native-session-executor.ts@@ -1,3 +1,4 @@+import { createRunPreparationTiming } from "../execution-preparation-timing.js";import { configuredEnvironment } from "../../vendor/paperclip-runner/index.js";import { apiKeyBillingType } from "@paperclipai/adapter-utils/api-billing-type";import { agents } from "@paperclipai/db";@@ -7673,6 +7674,7 @@ async function executePaperclipNativeSessionWithinScope("paperclip_runner_provider_unsupported: ACPX candidate requires exact host qualification authorization",);}+ const timeController = createRunPreparationTiming(input.execution.binding.runId, "native.controller");const preparationSpans = input.preparationSpans ?? [];const preparationStarts = nativeRunPreparationStarts(preparationSpans,@@ -8609,24 +8611,24 @@ async function executePaperclipNativeSessionWithinScope(try {if (input.managedGitHub && input.execution.schema !== "paperclip.native-execution-input.v6") {if (!input.execution.workspace.cwd) throw new Error("native_workspace_required");- githubAccess ??= await createNativeGitHubAccess({+ githubAccess ??= await timeController("github_access", () => createNativeGitHubAccess({scope: input.execution.binding,target: input.runnerExecutionTarget,- cwd: input.execution.workspace.cwd,+ cwd: input.execution.workspace.cwd!,env: resolveNativeProviderEnvironment(input.execution.provider, input.runnerEnvironment),resolveCredentials: (binding) => resolveGitHubOperationCredentials(input.db, binding),onLog: input.onLog,- });+ }));releaseGitHubRun = githubAccess.activate(input.execution.binding);input = { ...input, runnerEnvironment: { ...input.runnerEnvironment, ...githubAccess.env } };}- const expectedCurrentWakeComments = await resolveCurrentWakeCommentsBinding(+ const expectedCurrentWakeComments = await timeController("wake_binding", () => resolveCurrentWakeCommentsBinding(input.db,input.execution.binding,- );+ ));const runnerdBackend =input.useRunnerd && input.backend === undefined- ? await createRunnerdBackend({+ ? await timeController("backend_setup", () => createRunnerdBackend({...input,// Durable scope and prior-run verification use the controller's// canonical workspace identity. createRunnerdBackend separately@@ -8636,7 +8638,7 @@ async function executePaperclipNativeSessionWithinScope(durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId,trace,toolTrace,- })+ })): null;const remoteCleanupLease = input.runnerExecutionTarget?.kind === "remote" &&input.runnerExecutionTarget.transport === "sandbox" && input.runnerExecutionTarget.leaseId@@ -8966,7 +8968,7 @@ async function executePaperclipNativeSessionWithinScope(// A durable result remains successful if optional credential refresh// fails. Retire this owner so it cannot keep stale auth on a warm turn.if (warmSessionId !== null && lifecyclePolicy.mode === "warm") {- await releaseWarmNativeSession(warmSessionId, warmSessionOwnerToken, lifecyclePolicy.idleTimeoutMs, true);+ await timeController("warm_release", () => releaseWarmNativeSession(warmSessionId, warmSessionOwnerToken, lifecyclePolicy.idleTimeoutMs, true));}await input.onLog?.("stderr", "[paperclip-runner] managed credential refresh failed; provider session retired.\n");}@@ -9094,7 +9096,7 @@ async function executePaperclipNativeSessionWithinScope(if (settled) {await stoppedLeaseRenewal;if (warmSessionId !== null && lifecyclePolicy.mode === "warm") {- await releaseWarmNativeSession(warmSessionId, warmSessionOwnerToken, lifecyclePolicy.idleTimeoutMs, true);+ await timeController("warm_release", () => releaseWarmNativeSession(warmSessionId, warmSessionOwnerToken, lifecyclePolicy.idleTimeoutMs, true));}error = new NativeCancellationPendingRecoveryError();}@@ -9470,7 +9472,7 @@ async function executePaperclipNativeSessionWithinScope(// A startup failure or onSession(null) must not leak a transport. A warm// owner retains only the inactive broker until its normal retirement.if (githubAccess && (!warmSessionId || warmNativeSessions.get(warmSessionId)?.githubAccess !== githubAccess)) {- await githubAccess.stop();+ await timeController("github_stop", () => githubAccess!.stop());}}if (@@ -9499,7 +9501,7 @@ async function executePaperclipNativeSessionWithinScope(}}const releaseNow = new Date();- const released = await input.db+ const released = await timeController("coordinator_release", () => input.db.update(nativeRunFinalizations).set({leaseOwner: null,@@ -9525,7 +9527,7 @@ async function executePaperclipNativeSessionWithinScope(),).returning({ runId: nativeRunFinalizations.runId })- .then((rows) => rows[0] ?? null);+ .then((rows) => rows[0] ?? null));if (!released) throw new Error("native_session_lease_lost");const finalization: NativeFinalizationResult = {schema: "paperclip.native-finalization.v1",@@ -9558,7 +9560,7 @@ async function executePaperclipNativeSessionWithinScope(let collectInstructions: boolean;try {collectInstructions = Boolean(instructionCopy && ownedSession?.ownerToken === warmSessionOwnerToken &&- (instructionCopy.checkpointWarm ? !await instructionCopy.checkpointWarm() : await instructionCopy.hasChanges()));+ (instructionCopy.checkpointWarm ? !await timeController("instruction_checkpoint", () => instructionCopy.checkpointWarm!()) : await timeController("instruction_changes", () => instructionCopy.hasChanges())));} catch (error) {// A checkpoint or its receipt callback can reject. Retire this owner// before heartbeat stops the sandbox, preserving the initiating error.@@ -9573,13 +9575,13 @@ async function executePaperclipNativeSessionWithinScope(// requires the existing checkpoint-and-close boundary before collection.ownedSession.closeOnReleaseReason = "registered instruction edits require stopped-provider collection";}- await releaseWarmNativeSession(+ await timeController("warm_release", () => releaseWarmNativeSession(warmSessionId,warmSessionOwnerToken,lifecyclePolicy.idleTimeoutMs,!retainSession,- );- if (collectInstructions && !collectedByOwner) await instructionCopy!.collectStopped();+ ));+ if (collectInstructions && !collectedByOwner) await timeController("instruction_collection", () => instructionCopy!.collectStopped());}const providerFailure = providerFailureObservation.forTerminal(native.turnId, native.terminal);const adapterResult: AdapterExecutionResult = {@@ -11297,6 +11299,7 @@ async function createRunnerdBackendWithinSessionClaim(sessionScopeId: string,retainedTransition?: VerifiedWarmTransitionBinding,): Promise<NativeSessionBackend & { bindManagedSession(session: NativeSession): NativeSession }> {+ const timeController = createRunPreparationTiming(input.execution.binding.runId, "native.controller");let recoveryPending = retainedTransition !== undefined;const target = input.runnerExecutionTarget ?? { kind: "local" as const };const remoteTarget = target.kind === "remote" ? target : null;@@ -11313,13 +11316,13 @@ async function createRunnerdBackendWithinSessionClaim("runner_transport_ineligible: remote process runner is unavailable",);}- const currentWakeComments = await resolveCurrentWakeCommentsBinding(+ const currentWakeComments = await timeController("wake_binding", () => resolveCurrentWakeCommentsBinding(input.db,input.execution.binding,- );+ ));const pinnedSkills = new Set("runtimeContext" in input.execution ? input.execution.runtimeContext.skills.map((skill) => skill.key) : []);const connectorAssignments = [...pinnedSkills].some(isConnectorSkill)- ? await resolveConnectorAssignments(input.db, input.execution.binding) : [];+ ? await timeController("connector_assignments", () => resolveConnectorAssignments(input.db, input.execution.binding)) : [];const reviewRun = await input.db.select({ contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, input.execution.binding.runId),@@ -11347,12 +11350,12 @@ async function createRunnerdBackendWithinSessionClaim(throw new Error("assigned native MCP gateway path is invalid");}const assignedMcpTools = relayAssignedMcp && !nativeReview && assignedMcpUrl && assignedMcpToken- ? await createAssignedMcpTools({+ ? await timeController("assigned_mcp", () => createAssignedMcpTools({gateway: getAssignedMcpGateway(input.db),gatewayPublicId: assignedGatewayPublicId!,bearerToken: assignedMcpToken,workMode: input.execution.task.workMode,- })+ })): undefined;const dotAttachmentActor = input.execution.schema === "paperclip.native-execution-input.v6"? await input.db.select({ config: agents.adapterConfig }).from(agents).where(and(@@ -11398,7 +11401,7 @@ async function createRunnerdBackendWithinSessionClaim(ReturnType<SessionToolAuthorityEpoch["definitions"]>>;try {- dynamicTools = await authorityEpoch.definitions();+ dynamicTools = await timeController("tool_authority", () => authorityEpoch.definitions());} catch (error) {authorityEpoch.revoke();throw error;@@ -11429,7 +11432,7 @@ async function createRunnerdBackendWithinSessionClaim(const backend = createNativeSessionBackend(input.execution, {onSpawn: input.onSpawn, dynamicTools,dynamicToolHandler: async call => { await dotRunnerBroker(input.db).assertRunAuthority(input.execution as import("../../vendor/paperclip-runner/index.js").NativeExecutionInputV6); return authorityEpoch.execute(call); },- completionFeedback: async result => { await dotRunnerBroker(input.db).assertRunAuthority(input.execution as import("../../vendor/paperclip-runner/index.js").NativeExecutionInputV6); await authorityEpoch.definitions(); return nativeCompletionFeedback(input.db, input.execution.binding.runId, result); },+ completionFeedback: async result => { await dotRunnerBroker(input.db).assertRunAuthority(input.execution as import("../../vendor/paperclip-runner/index.js").NativeExecutionInputV6); await timeController("tool_authority", () => authorityEpoch.definitions()); return nativeCompletionFeedback(input.db, input.execution.binding.runId, result); },dotRunnerOptions: {stateDirectory: root, runnerBinary: remoteDot?.runnerBinary ?? resolvePaperclipRunnerBinary(),...(remoteDot ?? {}),@@ -11464,11 +11467,11 @@ async function createRunnerdBackendWithinSessionClaim(// Pi's explicit operator import supplies the target-platform authority. Never// substitute a Mac controller daemon or trust an image's self-reported hashes.// Existing explicit overrides and every other provider keep their old path.- const remotePiCompanion = await selectRemotePiCompanion({+ const remotePiCompanion = await timeController("companion_selection", () => selectRemotePiCompanion({provider: input.execution.provider, remote: remoteTarget !== null,binaryOverride: input.runnerRemoteBinaryPath, packOverride: input.runnerRemoteProviderPackPath,- workspaceRoot: input.execution.workspace.cwd,- });+ workspaceRoot: input.execution.workspace.cwd!,+ }));const configuredProviderPackRoot =input.runnerRemoteProviderPackPath?.trim() || remotePiCompanion?.providerPack || null;let expectedProviderPackManifest: RemoteProviderPackManifest | null = null;@@ -11505,7 +11508,7 @@ async function createRunnerdBackendWithinSessionClaim(// these exact bytes at remoteBinary before launch.const targetMatchedCodexArtifact = remoteTarget !== null && input.execution.provider.kind === "codex";const controllerRunnerBinary = targetMatchedCodexArtifact- ? await resolveRemotePaperclipRunnerBinary({ runner: remoteCommandRunner!, remoteCwd: remoteTarget.remoteCwd, configuredPath: input.runnerRemoteBinaryPath })+ ? await timeController("runner_binary", () => resolveRemotePaperclipRunnerBinary({ runner: remoteCommandRunner!, remoteCwd: remoteTarget.remoteCwd, configuredPath: input.runnerRemoteBinaryPath })): remoteTarget? input.runnerRemoteBinaryPath?.trim() || remotePiCompanion?.runnerBinary || (useBundledRemoteImageAssets ? bundledRemoteRunnerBinary() : resolvePaperclipRunnerBinary()): resolvePaperclipRunnerBinary();diff --git a/server/src/startup-recovery-timing.test.ts b/server/src/startup-recovery-timing.test.tsnew file mode 100644index 0000000000..cb98e7a914--- /dev/null+++ b/server/src/startup-recovery-timing.test.ts@@ -0,0 +1,68 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { timeStartupRecovery } from "./startup-recovery-timing.js";++const handles = vi.hoisted(() => ({+ startSpan: vi.fn(),+ getTracer: vi.fn(),+}));+vi.mock("@opentelemetry/api", () => ({+ ROOT_CONTEXT: "root",+ SpanStatusCode: { ERROR: 2 },+ trace: { getTracer: handles.getTracer },+}));++beforeEach(() => {+ vi.unstubAllEnvs();+ vi.clearAllMocks();+ handles.getTracer.mockReturnValue({ startSpan: handles.startSpan });+});+afterEach(() => vi.unstubAllEnvs());++it.each([undefined, "", " "])("runs silently without tracing for endpoint %s", async endpoint => {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", endpoint);+ const spies = ["log", "info", "warn", "error", "debug"].map(name => vi.spyOn(console, name as "log"));+ try {+ const value = {};+ const error = new Error("private failure");+ await expect(timeStartupRecovery("accounting", async () => value)).resolves.toBe(value);+ await expect(timeStartupRecovery("native_recovery", async () => { throw error; })).rejects.toBe(error);+ expect(handles.getTracer).not.toHaveBeenCalled();+ for (const spy of spies) expect(spy).not.toHaveBeenCalled();+ } finally { for (const spy of spies) spy.mockRestore(); }+});++it("keeps the phase open until recovery settles and records no results or error text", async () => {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test");+ const span = { end: vi.fn(), setStatus: vi.fn() };+ handles.startSpan.mockReturnValue(span);+ let reject!: (error: Error) => void;+ const work = vi.fn(() => new Promise<void>((_resolve, fail) => { reject = fail; }));+ const pending = timeStartupRecovery("native_recovery", work);+ expect(handles.startSpan).toHaveBeenCalledExactlyOnceWith("controller.startup.native_recovery", undefined, "root");+ expect(span.end).not.toHaveBeenCalled();+ const error = new Error("private database detail");+ const assertion = expect(pending).rejects.toBe(error);+ reject(error);+ await assertion;+ expect(work).toHaveBeenCalledOnce();+ expect(span.setStatus).toHaveBeenCalledExactlyOnceWith({ code: 2 });+ expect(span.end).toHaveBeenCalledOnce();+});++it.each(["lookup", "start", "end", "status"])("preserves one execution when tracing fails during %s", async failure => {+ vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test");+ const broken = () => { throw new Error("tracing unavailable"); };+ handles.getTracer.mockImplementation(failure === "lookup" ? broken : () => ({ startSpan: handles.startSpan }));+ handles.startSpan.mockImplementation(failure === "start" ? broken : () => ({+ end: failure === "end" ? broken : vi.fn(),+ setStatus: failure === "status" ? broken : vi.fn(),+ }));+ const value = {};+ const work = vi.fn(async () => value);+ await expect(timeStartupRecovery("orphan_reaping", work)).resolves.toBe(value);+ expect(work).toHaveBeenCalledOnce();+ const error = new Error("original failure");+ const failedWork = vi.fn(async () => { throw error; });+ await expect(timeStartupRecovery("queued_runs", failedWork)).rejects.toBe(error);+ expect(failedWork).toHaveBeenCalledOnce();+});diff --git a/server/src/startup-recovery-timing.ts b/server/src/startup-recovery-timing.tsnew file mode 100644index 0000000000..cbcc1da630--- /dev/null+++ b/server/src/startup-recovery-timing.ts@@ -0,0 +1,23 @@+import { ROOT_CONTEXT, SpanStatusCode, trace, type Span } from "@opentelemetry/api";++type StartupRecoveryPhase = "tool_reviews" | "gateway_sessions" | "delivery_workers"+ | "accounting" | "plugin_workers" | "native_recovery" | "hot_restart"+ | "orphan_reaping" | "scheduled_retries" | "queued_runs" | "goal_actions" | "active_goals";++export async function timeStartupRecovery<T>(phase: StartupRecoveryPhase, work: () => Promise<T>): Promise<T> {+ if (!process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim()) return work();+ let span: Span | undefined;+ try {+ span = trace.getTracer("paperclip.controller-startup").startSpan(+ `controller.startup.${phase}`, undefined, ROOT_CONTEXT,+ );+ } catch {}+ try {+ return await work();+ } catch (error) {+ try { span?.setStatus({ code: SpanStatusCode.ERROR }); } catch {}+ throw error;+ } finally {+ try { span?.end(); } catch {}+ }+}