feat: add a no-op OpenTelemetry span seam for the sandbox startup path (#10522)

## Thinking Path

> - Paperclip helps people run and govern AI agent work
> - Sandbox startup needs a safe place to add telemetry spans without
forcing OpenTelemetry on every run
> - This change adds a no-op span seam, so the startup path can accept a
tracer later and still stay inert now
> - The server gets a lazy tracer accessor, and the adapter timing
helper gets an injected tracer hook
> - The change keeps the default path free of OpenTelemetry and keeps
the existing startup event path unchanged
> - The benefit is a future-safe seam with no runtime change today

## Linked Issues or Issue Description

This PR addresses a feature gap in the sandbox startup path.

### Problem

Sandbox startup has no safe span seam. A direct OpenTelemetry import
would load telemetry packages on every run.

### Proposed Solution

Add a lazy tracer accessor in the server. Add an injected no-op tracer
seam in startup timing.

### Alternatives

Import OpenTelemetry directly in the startup path. Reject that path
because the default startup flow must stay inert.

## What Changed

- Added a lazy startup tracer accessor in
`server/src/instrumentation.ts`.
- Added an injected startup tracer seam in
`packages/adapter-utils/src/acpx-engine/startup-timing.ts`.
- Kept the startup event path unchanged.
- Kept `adapter-utils` free of OpenTelemetry imports.

## Verification

- `pnpm exec vitest run
packages/adapter-utils/src/acpx-engine/startup-timing.test.ts`
- `pnpm exec vitest run server/src/__tests__/instrumentation.test.ts`
- `tsc --noEmit` for `@paperclipai/adapter-utils` and
`@paperclipai/server`

## Risks

Low risk. The default tracer is a no-op, so the runtime path stays inert
until a later change injects a real tracer.

## Model Used

OpenAI GPT-5. Tool use and code execution.

## 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 found none
- [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 or instance-local Paperclip issues
or links
- [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
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-07-30 18:23:44 -07:00
1 parent 7cfb655f60
commit 740554acc6
4 files changed
+481 -10

No files matched your search

@@ -87,6 +87,44 @@ describe("instrumentationReady", () => {
});
});
describe("getStartupTracer", () => {
it("returns a usable tracer-shaped object when OTEL_EXPORTER_OTLP_ENDPOINT is unset", async () => {
const { getStartupTracer } = await importFreshInstrumentation();
const tracer = getStartupTracer();
// The accessor never returns null. The result exposes the span surface the
// startup seam calls, so the caller needs no null check.
expect(tracer).not.toBeNull();
expect(typeof tracer.startSpan).toBe("function");
// A no-op tracer must open and end a span without throwing.
expect(() => tracer.startSpan("workspace.resolve").end()).not.toThrow();
});
it("loads no OTel SDK package when the endpoint is unset", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { getStartupTracer, instrumentationReady } = await importFreshInstrumentation();
// The endpoint is unset, so the bootstrap never runs and no SDK package
// import is attempted; readiness resolves at once.
await expect(instrumentationReady).resolves.toBeUndefined();
// The accessor still returns a usable tracer even though no @opentelemetry
// SDK package is installed. That proves it never imported the SDK: a hard
// dependency on the SDK would throw here instead.
const tracer = getStartupTracer();
expect(typeof tracer.startSpan).toBe("function");
expect(() => tracer.startSpan("stage.sync").end()).not.toThrow();
// The bootstrap "packages are not installed" diagnostic must not fire on
// this path. That message comes only from the endpoint-set bootstrap.
for (const call of warn.mock.calls) {
expect(String(call[0])).not.toContain("@opentelemetry/* packages are not installed");
}
});
});
describe("shutdownInstrumentation", () => {
it("is a no-op when tracing is off and idempotent across calls", async () => {
const { shutdownInstrumentation } = await importFreshInstrumentation();
+66
View File
@@ -26,11 +26,77 @@
// exit via `shutdownInstrumentation()`, which index.ts awaits in its signal
// handler before `process.exit`.
import { createRequire } from "node:module";
const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
let sdkShutdown: (() => Promise<void>) | null = null;
let shutdownPromise: Promise<void> | null = null;
/**
* A minimal, structural span/tracer surface. It is the subset of the
* `@opentelemetry/api` `Span` / `Tracer` shape that the startup timing seam
* calls. A real OTel tracer satisfies it. The no-op fallback below implements
* it too, so the caller never needs a null check.
*/
interface StartupTracerHandle {
startSpan(
name: string,
options?: unknown,
): {
setAttribute(key: string, value: unknown): void;
setStatus(status: { code: number; message?: string }): void;
end(): void;
};
}
const NOOP_SPAN = {
setAttribute() {},
setStatus() {},
end() {},
};
/**
* The no-op tracer returned when `@opentelemetry/api` is absent or a lookup
* fails. It opens a span that does nothing, so startup tracing stays a no-op
* without an installed OTel package.
*/
const NOOP_TRACER: StartupTracerHandle = {
startSpan: () => NOOP_SPAN,
};
let tracerApiLoadFailed = false;
/**
* Return a startup tracer. When `@opentelemetry/api` is installed, it returns
* `trace.getTracer(name)`. The `api` package itself returns a no-op tracer
* while no SDK is registered, so an unset endpoint still yields a safe no-op
* without loading any OTel SDK package. The api package loads lazily through
* `require`, so the module graph stays OTel-free until the first call. The
* accessor never throws: a load or lookup failure logs once and returns the
* local no-op tracer (fail open).
*/
export function getStartupTracer(name = "paperclip.startup"): StartupTracerHandle {
try {
const require = createRequire(import.meta.url);
const api = require("@opentelemetry/api") as {
trace?: { getTracer(n: string): StartupTracerHandle };
};
const tracer = api.trace?.getTracer(name);
return tracer ?? NOOP_TRACER;
} catch (err) {
if (!tracerApiLoadFailed) {
tracerApiLoadFailed = true;
// eslint-disable-next-line no-console
console.warn(
"[paperclip] @opentelemetry/api is not available; startup tracing uses a no-op tracer.",
err,
);
}
return NOOP_TRACER;
}
}
/**
* Resolves once the OTel SDK has started (or once bootstrap has failed and
* logged, or immediately when the feature is off). Await before constructing