From 0c3ed144cb1d14585e4dd9f9056df236b9290cf7 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Tue, 24 Nov 2026 18:08:46 -0800 Subject: [PATCH] Label opt-in traces with the public instance hostname (#22856) --- doc/browser-performance-tracing.md | 3 +- doc/observability.md | 6 +++ packages/shared/src/validators/access.ts | 1 + .../__tests__/browser-tracing-config.test.ts | 3 ++ .../__tests__/instrumentation-signals.test.ts | 43 +++++++++++++++++-- server/src/browser-tracing-config.ts | 2 + server/src/instrumentation.ts | 31 +++++++------ server/src/tracing-instance-host.ts | 5 +++ .../runner-e2e/source-sdk-public-inputs.json | 2 +- ui/src/lib/browser-tracing/sdk.test.ts | 4 +- ui/src/lib/browser-tracing/sdk.ts | 1 + ui/src/lib/browser-tracing/span-sanitizer.ts | 1 + 12 files changed, 83 insertions(+), 19 deletions(-) create mode 100644 server/src/tracing-instance-host.ts diff --git a/doc/browser-performance-tracing.md b/doc/browser-performance-tracing.md index e3b5ea04d45..bb6f6a52c9c 100644 --- a/doc/browser-performance-tracing.md +++ b/doc/browser-performance-tracing.md @@ -272,7 +272,8 @@ Attributes (the complete allowlist): | `SampleRate` | all, when sampling | 1-in-N weight | Resource: `service.name`, `service.version` (the UI build commit), -`deployment.environment.name`. +`deployment.environment.name`, and `paperclip.instance.host` when +`PAPERCLIP_TRACING_INSTANCE_HOST=true` and a public HTTP(S) URL is configured. Not sent: URLs, paths with ids, query strings, hashes, referrers, user agent, user, company, or task identifiers, titles, or content. Server spans carry no diff --git a/doc/observability.md b/doc/observability.md index 66010479c8c..68a76b555f8 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -100,6 +100,12 @@ export OTEL_SERVICE_NAME="paperclip" export OTEL_SERVICE_VERSION="2026.5.0" ``` +When `PAPERCLIP_TRACING_INSTANCE_HOST=true`, server and browser traces include +`paperclip.instance.host` from the hostname in the configured `PAPERCLIP_PUBLIC_URL`. +Server spans read the current URL at span start. Browser sessions receive the +hostname with their tracing configuration. Paths, query strings, ports, and +credentials are excluded. The setting is off by default. + ### `service.version` resolution order The `service.version` span attribute reports the commit the running server was diff --git a/packages/shared/src/validators/access.ts b/packages/shared/src/validators/access.ts index b89c803b03d..987401ab5c3 100644 --- a/packages/shared/src/validators/access.ts +++ b/packages/shared/src/validators/access.ts @@ -207,6 +207,7 @@ export type CurrentUserProfile = z.infer; * needs no key); it is never a configuration key. */ export const browserTracingConfigSchema = z.object({ + instanceHost: z.string().min(1).optional(), tracesUrl: z.string().url(), ingestKey: z.string().min(1).nullable(), serviceName: z.string().min(1), diff --git a/server/src/__tests__/browser-tracing-config.test.ts b/server/src/__tests__/browser-tracing-config.test.ts index db2f9366a1c..49fd4ab0e10 100644 --- a/server/src/__tests__/browser-tracing-config.test.ts +++ b/server/src/__tests__/browser-tracing-config.test.ts @@ -23,12 +23,15 @@ describe("resolveBrowserTracingConfig", () => { PAPERCLIP_BROWSER_TRACES_ENDPOINT: "https://api.honeycomb.io", PAPERCLIP_BROWSER_TRACES_INGEST_KEY: ingestKey, SENTRY_ENVIRONMENT: "staging", + PAPERCLIP_TRACING_INSTANCE_HOST: "true", + PAPERCLIP_PUBLIC_URL: "https://demo.example.com/private", }); expect(config).toEqual({ tracesUrl: "https://api.honeycomb.io/v1/traces", ingestKey, serviceName: "paperclip-web", environment: "staging", + instanceHost: "demo.example.com", sampleRate: 1, }); expect(authSessionSchema.shape.browserTracing.parse(config)).toEqual(config); diff --git a/server/src/__tests__/instrumentation-signals.test.ts b/server/src/__tests__/instrumentation-signals.test.ts index 44e5638b83a..6c6e18921c8 100644 --- a/server/src/__tests__/instrumentation-signals.test.ts +++ b/server/src/__tests__/instrumentation-signals.test.ts @@ -1,16 +1,27 @@ import { afterEach, expect, it, vi } from 'vitest'; +import { InMemorySpanExporter, TracerProvider, type SpanProcessor } from '@opentelemetry/sdk-trace'; const sdk = vi.hoisted(() => ({ options: [] as Array>, start: vi.fn(), shutdown: vi.fn(async () => {}) })); vi.mock('../peer-version-check.js', () => ({ checkExactPeerVersions: () => ({ ok: true }) })); -vi.mock('@opentelemetry/sdk-node', () => ({ NodeSDK: class { +vi.mock('@opentelemetry/sdk-node', async () => { + const { BatchSpanProcessor } = await import('@opentelemetry/sdk-trace'); + return { tracing: { BatchSpanProcessor: class extends BatchSpanProcessor { + constructor(exporter: InMemorySpanExporter) { super({ exporter }); } + } }, NodeSDK: class { constructor(options: Record) { sdk.options.push(options); } start = sdk.start; shutdown = sdk.shutdown; -} })); + } }; +}); vi.mock('@opentelemetry/auto-instrumentations-node', () => ({ getNodeAutoInstrumentations: () => [] })); vi.mock('@opentelemetry/resources', () => ({ resourceFromAttributes: (attributes: unknown) => attributes })); vi.mock('@opentelemetry/semantic-conventions', () => ({ ATTR_SERVICE_NAME: 'service.name', ATTR_SERVICE_VERSION: 'service.version' })); -vi.mock('@opentelemetry/exporter-trace-otlp-http', () => ({ OTLPTraceExporter: class {} })); +let capturedExporter: InMemorySpanExporter; +vi.mock('@opentelemetry/exporter-trace-otlp-http', () => ({ + OTLPTraceExporter: class extends InMemorySpanExporter { + constructor() { super(); capturedExporter = this; } + }, +})); afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); }); it('configures current plural SDK signal options so an opted-in trace exporter cannot enable default metrics or logs', async () => { @@ -28,3 +39,29 @@ it('configures current plural SDK signal options so an opted-in trace exporter c await instrumentation.shutdownInstrumentation(); expect(sdk.shutdown).toHaveBeenCalledOnce(); }); + +it('labels spans with the current public hostname after an identity change', async () => { + vi.stubEnv('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://collector.invalid:4318'); + vi.stubEnv('OTEL_EXPORTER_OTLP_PROTOCOL', 'http/json'); + vi.stubEnv('PAPERCLIP_TRACING_INSTANCE_HOST', 'true'); + vi.stubEnv('PAPERCLIP_PUBLIC_URL', 'https://first.example.com/private?q=query'); + vi.spyOn(process, 'once').mockReturnValue(process); + vi.resetModules(); + const instrumentation = await import('../instrumentation.js'); + await instrumentation.instrumentationReady; + const provider = new TracerProvider({ spanProcessors: sdk.options.at(-1)!.spanProcessors as SpanProcessor[] }); + try { + const tracer = provider.getTracer('test'); + tracer.startSpan('first').end(); + vi.stubEnv('PAPERCLIP_PUBLIC_URL', 'https://second.example.com'); + tracer.startSpan('second').end(); + vi.stubEnv('PAPERCLIP_PUBLIC_URL', 'invalid'); + tracer.startSpan('invalid').end(); + await provider.forceFlush(); + expect(capturedExporter.getFinishedSpans().map(s => s.attributes['paperclip.instance.host'])) + .toEqual(['first.example.com', 'second.example.com', undefined]); + } finally { + await provider.shutdown(); + } + await instrumentation.shutdownInstrumentation(); +}); diff --git a/server/src/browser-tracing-config.ts b/server/src/browser-tracing-config.ts index b5a4d6310a0..530b02fa47c 100644 --- a/server/src/browser-tracing-config.ts +++ b/server/src/browser-tracing-config.ts @@ -11,6 +11,7 @@ // Every invalid setting fails closed: the browser receives `null` and the // server logs one warning naming the variable, never its value. +import { tracingInstanceHost } from "./tracing-instance-host.js"; import type { BrowserTracingConfig } from "@paperclipai/shared"; import { isCloudManagedInstance, type CloudInstanceEnv } from "./services/cloud-instance.js"; @@ -95,6 +96,7 @@ export function resolveBrowserTracingConfig( } return { + instanceHost: tracingInstanceHost(env), tracesUrl: browserTracesUrl(endpoint), ingestKey, serviceName: normalize(env.PAPERCLIP_BROWSER_TRACES_SERVICE_NAME) ?? BROWSER_TRACES_DEFAULT_SERVICE_NAME, diff --git a/server/src/instrumentation.ts b/server/src/instrumentation.ts index d26b09ceae4..1e2acce901f 100644 --- a/server/src/instrumentation.ts +++ b/server/src/instrumentation.ts @@ -35,6 +35,7 @@ import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { createRequire } from "node:module"; +import { tracingInstanceHost } from "./tracing-instance-host.js"; import { checkExactPeerVersions } from "./peer-version-check.js"; export { checkExactPeerVersions } from "./peer-version-check.js"; @@ -498,6 +499,9 @@ async function bootstrapOtel(endpoint: string): Promise { // eslint-disable-next-line no-console console.log(`[paperclip] OpenTelemetry service.version=${serviceVersion}`); + const exporter = (protocol === "grpc" + ? new OTLPTraceExporter({ url: endpoint }) + : new OTLPTraceExporter()) as never; const sdk = new NodeSDK({ // This integration exports traces only. NodeSDK otherwise creates // default OTLP metric/log exporters even when none were configured. @@ -507,19 +511,20 @@ async function bootstrapOtel(endpoint: string): Promise { [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || "paperclip", [ATTR_SERVICE_VERSION]: serviceVersion, }), - // For the HTTP protocols OTEL_EXPORTER_OTLP_ENDPOINT is a *base* URL - // and the exporter appends /v1/traces only when it reads the env var - // itself — an explicit `url` is used verbatim and would silently POST - // to the wrong path. Pass `url` only for gRPC, which has no path. - // `importExporter` types `OTLPTraceExporter` as `=> unknown` so the - // module graph stays free of the optional OTLP/SDK packages. Without - // that type, `traceExporter` needs `SpanExporter`, and an import of - // `SpanExporter` breaks the compile when the optional packages are - // absent. Cast to `never` instead: `never` is assignable to - // `SpanExporter` and needs no import. - traceExporter: (protocol === "grpc" - ? new OTLPTraceExporter({ url: endpoint }) - : new OTLPTraceExporter()) as never, + ...(process.env.PAPERCLIP_TRACING_INSTANCE_HOST === "true" ? { + spanProcessors: [ + { + onStart(span: { setAttribute(name: string, value: string): unknown }) { + const host = tracingInstanceHost(process.env); + if (host) span.setAttribute("paperclip.instance.host", host); + }, + onEnd() {}, + async forceFlush() {}, + async shutdown() {}, + }, + new sdkNode.tracing.BatchSpanProcessor(exporter), + ], + } : { traceExporter: exporter }), instrumentations: [ getNodeAutoInstrumentations({ // Too chatty for this workload. diff --git a/server/src/tracing-instance-host.ts b/server/src/tracing-instance-host.ts new file mode 100644 index 00000000000..10d47223942 --- /dev/null +++ b/server/src/tracing-instance-host.ts @@ -0,0 +1,5 @@ +export function tracingInstanceHost(env: NodeJS.ProcessEnv): string | undefined { + if (env.PAPERCLIP_TRACING_INSTANCE_HOST !== "true" || !env.PAPERCLIP_PUBLIC_URL) return; + const url = URL.parse(env.PAPERCLIP_PUBLIC_URL); + if (url?.protocol === "https:" || url?.protocol === "http:") return url.hostname; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index c85aa71ed6c..8e838418752 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -471,7 +471,7 @@ "packages/shared/src/types/workspace-runtime.ts": "00ab237577d3ea3a1fa946ce6ab6ef8b389b1739", "packages/shared/src/types/workspace-source-verification.ts": "647f5c8817590629439813df5dc63750b316206d", "packages/shared/src/validators/access.test.ts": "0df0e096658a31c4f21462a992e38cf8bd7082b1", - "packages/shared/src/validators/access.ts": "b89c803b03d7bd966ecd4b079ccb445b2a8ffb15", + "packages/shared/src/validators/access.ts": "987401ab5c3c352c9417071f78b960857d7fe65f", "packages/shared/src/validators/adapter-auth-session.ts": "14cffbd7281265bf3f059bcf1b97739ebe0e1f81", "packages/shared/src/validators/adapter-registry.test.ts": "567c113e50dd0c0d259b095375f8f8f403ffa893", "packages/shared/src/validators/adapter-registry.ts": "6fb9f655d49f774ef7f082bf842f388f1187e545", diff --git a/ui/src/lib/browser-tracing/sdk.test.ts b/ui/src/lib/browser-tracing/sdk.test.ts index 082e1d6621d..5d236770463 100644 --- a/ui/src/lib/browser-tracing/sdk.test.ts +++ b/ui/src/lib/browser-tracing/sdk.test.ts @@ -60,7 +60,7 @@ describe("startTracingSdk", () => { it("exports a page.load span with the route template and only allowlisted attributes", async () => { const recorder = idleRecorder(); - handle = startTracingSdk(config, recorder, { exporter }); + handle = startTracingSdk({ ...config, instanceHost: "demo.example.com" }, recorder, { exporter }); recorder.begin({ routeTemplate: "/:companyPrefix/issues/:issueId", loadType: "client", startTime: performance.now() }); (recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames(); await handle.forceFlush(); @@ -78,8 +78,10 @@ describe("startTracingSdk", () => { // service.version is the build commit, absent in tests. expect(Object.keys(spans[0]!.resource.attributes).sort()).toEqual([ "deployment.environment.name", + "paperclip.instance.host", "service.name", ]); + expect(spans[0]!.resource.attributes["paperclip.instance.host"]).toBe("demo.example.com"); expect(spans[0]!.resource.attributes["service.name"]).toBe("paperclip-web"); }); diff --git a/ui/src/lib/browser-tracing/sdk.ts b/ui/src/lib/browser-tracing/sdk.ts index aaddd955d4b..84835b90eda 100644 --- a/ui/src/lib/browser-tracing/sdk.ts +++ b/ui/src/lib/browser-tracing/sdk.ts @@ -224,6 +224,7 @@ export function startTracingSdk( const provider = new WebTracerProvider({ resource: resourceFromAttributes({ "service.name": config.serviceName, + ...(config.instanceHost ? { "paperclip.instance.host": config.instanceHost } : {}), ...(buildCommit ? { "service.version": buildCommit } : {}), ...(config.environment ? { "deployment.environment.name": config.environment } : {}), }), diff --git a/ui/src/lib/browser-tracing/span-sanitizer.ts b/ui/src/lib/browser-tracing/span-sanitizer.ts index b93247eb3c0..06dc0d4d594 100644 --- a/ui/src/lib/browser-tracing/span-sanitizer.ts +++ b/ui/src/lib/browser-tracing/span-sanitizer.ts @@ -34,6 +34,7 @@ export const ALLOWED_SPAN_ATTRIBUTES: ReadonlySet = new Set([ ]); export const ALLOWED_RESOURCE_ATTRIBUTES: ReadonlySet = new Set([ + "paperclip.instance.host", "service.name", "service.version", "deployment.environment.name",