Skip to content

feat: removing vtex/diagnostics-nodejs - #3389

Merged
ommeirelles merged 29 commits into
devfrom
feat/otel-logger
Aug 11, 2026
Merged

ommeirelles merged 29 commits into
devfrom
feat/otel-logger

Conversation

@ommeirelles

@ommeirelles ommeirelles commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Testing OTEL without @vtex/diagnostics-nodejs

Summary by CodeRabbit

  • New Features
    • Added OpenTelemetry-based tracing for GraphQL with per-request root spans.
    • Enabled OTLP trace and log exporting, including automatic log capture from console.
    • Increased default trace sampling rate.
  • Bug Fixes
    • More consistent resolver span lifecycle and error reporting for both sync and async failures.
  • Chores
    • Updated analytics service naming and simplified telemetry enablement configuration.
  • Tests
    • Updated telemetry mocks and integration/unit tests.

SFS-3279
SFS-3219

@ommeirelles
ommeirelles requested a review from a team as a code owner June 12, 2026 14:07
@ommeirelles
ommeirelles requested review from gabpaladino and renatamottam and removed request for a team June 12, 2026 14:07
@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Migrate from VTEX diagnostics-nodejs to native OpenTelemetry NodeSDK: bootstrap OTLP exporters for traces and logs, convert global client Maps to singletons, expand OTEL options typing to carry injected __otelContext, rewrite ResolverTrace to extract context and manage span lifetime across sync/Promise paths with centralized error handling, add per-request root spans in GraphQL execution, inject OTEL context through server options, and update configuration/tests.

Changes

OpenTelemetry SDK Migration

Layer / File(s) Summary
OTLP exporters and NodeSDK bootstrap
packages/diagnostics/src/tracer.ts, packages/diagnostics/src/start.ts
Add traceExporter() that builds OTLP gRPC BatchSpanProcessor with smart credential selection (TLS by default, insecure for localhost/dev). Rewrite getTelemetryClient to initialize NodeSDK with span processor and HttpInstrumentation, start the SDK, add SIGTERM shutdown handler that closes logs then SDK.
Logger provider and OTLP log exporter
packages/diagnostics/src/logger.ts
Implement setupLogs(resource) that caches and returns existing LoggerProvider if present, otherwise selects OTLP logs endpoint, chooses gRPC credentials (insecure for local/dev), creates LoggerProvider with BatchLogRecordProcessor and OTLPLogExporter, registers globally, caches singleton, and wraps console in a Proxy to emit OpenTelemetry log records while preserving original console behavior.
Package exports, types, build config, and sampling
packages/diagnostics/package.json, packages/diagnostics/vite.config.mts, packages/diagnostics/configs/prod.json
Update package.json type/default export paths to new dist locations, replace @vtex/diagnostics-nodejs/resolve-pkg with @grpc/grpc-js and OpenTelemetry packages, adjust Vite sourcemap to always inline and remove @vtex/diagnostics-nodejs from externals, raise production trace default sampling from 0.01 to 0.3.
Global type contracts and diagnostics initialization
packages/diagnostics/@types/global.d.ts, packages/diagnostics/src/globals.ts, packages/diagnostics/src/index.ts
Replace fsDiagnostics Maps (TELEMETRY_CLIENTS/TRACE_CLIENTS) with optional singleton clients (TELEMETRY_CLIENT/TRACE_CLIENT/LOGGER_CLIENT), add OTLP_TRACES_ENDPOINT/OTLP_LOGGER_ENDPOINT strings, compute IS_DEV from process.env; update global.d.ts to import OTel types; narrow re-exports to getTelemetryClient only.
OTEL options type expansion
packages/api/src/typings/globals.ts
Change Options.OTEL from optional structured object to required Record<string, any> to carry injected __otelContext.
ResolverTrace span creation, context, and error handling
packages/api/src/observability/telemetry.ts
Rewrite to use OTELAPI.trace.getTracer('Graphql'), start INTERNAL span with resolver attributes, extract context from graphqlContext.OTEL.__otelContext, install span via OTELAPI.trace.setSpan, execute in that context. Sync returns end span immediately; Promise fulfillment ends in .then(...); rejections route through catchError which sets ERROR, records exception, ends span, logs, and returns error.
VTEX context factory OTEL extraction
packages/api/src/platforms/vtex/index.ts
Update GraphqlVtexContextFactory to extract propagation context from options.OTEL.__otelContext instead of options.OTEL directly.
Server root span instrumentation
packages/core/src/server/index.ts
Import OTELAPI, wrap GraphQL execution in per-request span named graphql ${operationName}, activate context via OTELAPI.context.with(...) so resolver spans parent correctly, set error status and record exceptions on failure, end span in finally block.
Server options injection and telemetry client wiring
packages/core/src/server/options.ts
Refactor withTraceClient to await getTelemetryClient, force OTEL.enabled: true, initialize OTEL.__otelContext; switch imports from getTraceClient to getTelemetryClient.
Instrumentation gate and config updates
packages/core/src/instrumentation.ts, packages/core/discovery.config.default.js, packages/core/next.config.js
Remove otelEnabled gate, gate telemetry client init only on NEXT_RUNTIME === 'nodejs'; fix console log typo; update discovery serviceName to faststore and remove otelEnabled; hardcode analytics enabled.
Test mocks, OTEL options, and test fixtures
packages/core/test/server/index.test.ts, packages/api/test/unit/..., packages/api/test/integration/..., packages/api/test/mocks/*
Mock @faststore/diagnostics in server tests; add OTEL: { __otelContext: {} } to all integration/unit test apiOptions; add showSponsored=false to product search mock.

Sequence Diagram

sequenceDiagram
  participant GraphQL Request Handler as req
  participant CoreServer as execute()
  participant RootSpan as root span
  participant Resolver as ResolverTrace()
  participant ResolverSpan as resolver span
  req->>CoreServer: execute GraphQL
  CoreServer->>RootSpan: create span graphql operation
  CoreServer->>RootSpan: set active context
  CoreServer->>Resolver: run resolvers in context
  Resolver->>ResolverSpan: create INTERNAL span
  Resolver->>ResolverSpan: set span on extracted __otelContext
  Resolver->>ResolverSpan: execute resolver
  alt resolve sync
    Resolver-->>ResolverSpan: end() immediately
  else resolve Promise
    ResolverSpan->>ResolverSpan: end() on .then()
  else reject Promise
    ResolverSpan->>ResolverSpan: catchError() setStatus(ERROR) recordException() end()
  end
  Resolver-->>CoreServer: result
  CoreServer->>RootSpan: end() in finally
  CoreServer-->>req: { data, errors, extensions }
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • vtex/faststore#3215: Both PRs modify packages/api/src/observability/telemetry.ts ResolverTrace tracing flow and span lifecycle; this PR continues span instrumentation improvements from the context/error handling foundations laid in #3215.

Suggested reviewers

  • gabpaladino
  • lemagnetic

OTel SDK spins, endpoints gleam bright,
Spans cascade through requests, context set right,
Traces and logs now flow with native grace,
Errors caught quick in their proper place,
FastStore hums with observability's light. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main change: replacing and removing @vtex/diagnostics-nodejs in favor of OTEL.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/otel-logger

Comment @coderabbitai help to get the list of available commands.

@codesandbox-ci

codesandbox-ci Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@pkg-pr-new

pkg-pr-new Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@de863ef

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@de863ef

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@de863ef

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@de863ef

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@de863ef

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@de863ef

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@de863ef

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@de863ef

commit: de863ef

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

🧹 Nitpick comments (2)
packages/core/test/server/index.test.ts (1)

21-29: ⚡ Quick win

Return a stable mock context from setSpan().

withTraceClient() now passes the return value of trace.setSpan() into propagation.inject(), but this mock returns undefined, so the test can still pass if that propagation handoff breaks.

Suggested fix
 vi.mock('`@faststore/diagnostics`', () => {
+  const mockContext = {}
   const mockSpan = {
     setStatus: vi.fn(),
     recordException: vi.fn(),
     end: vi.fn(),
   }

   return {
@@
       trace: {
         getTracer: vi.fn(() => ({
           startSpan: vi.fn(() => mockSpan),
         })),
-        setSpan: vi.fn(),
+        setSpan: vi.fn(() => mockContext),
       },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/test/server/index.test.ts` around lines 21 - 29, The mock for
trace.setSpan used in tests should return a stable context object so
withTraceClient() passes a real value into propagation.inject(); update the mock
implementation referenced as setSpan (and any usages in withTraceClient() test
setup) to return a consistent object (e.g., an empty context {} or a named
mockContext) and ensure propagation.inject is called with that returned object
instead of undefined.
packages/diagnostics/configs/prod.json (1)

4-8: Watch the production ingest/cost impact of the new default sampling rate.

Moving the default trace rate from 1% to 30% is a big observability-volume jump. I’d want dashboards/alerts on exporter failures, queue pressure, and ingest cost before rolling this out broadly.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/diagnostics/configs/prod.json` around lines 4 - 8, The prod config
raised the global sampling from 1% to 30% (defaultRate and the "trace_all"
rule's sampleRate both set to 0.3), which will massively increase ingest/cost;
revert defaultRate and the "trace_all" sampleRate back to 0.01 (1%) or gate the
0.3 change behind a feature flag/gradual rollout, and add instrumentation and
alerts for exporter failures, queue pressure, and ingest cost before enabling
the higher rate cluster-wide; ensure the fix updates the JSON entries for
"defaultRate" and the rule named "trace_all" and document the rollout plan.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/api/src/observability/telemetry.ts`:
- Around line 39-48: The extracted OTEL context built with
OTELAPI.propagation.extract and the span set via OTELAPI.trace.setSpan is not
activated before invoking the resolver, so calls to fn(...) still run in the
previous active context; wrap the resolver invocation in
OTELAPI.context.with(theExtractedContext, () => fn(source, vars, graphqlContext,
info)) (using the same span/context you created) to activate the new context for
downstream spans and return its result, ensuring errors are propagated out of
the context wrapper.
- Around line 47-58: The span is ending before async resolvers finish because
the code returns fn(...) directly; change the try block in telemetry wrapper so
you await the resolver result instead of returning it immediately: replace the
direct "return fn(source, vars, graphqlContext, info)" with something like
"const result = fn(source, vars, graphqlContext, info); const awaited = await
result; return awaited" (or simply "return await fn(...)") so the finally block
(span?.end()) runs only after async resolvers settle; update in the function
that references fn, span, and resolverName in telemetry.ts.

In `@packages/api/src/platforms/vtex/index.ts`:
- Around line 43-45: GraphqlVtexContextFactory is crashing because
OTELAPI.propagation.extract is dereferencing options.OTEL.__otelContext even
when options.OTEL is undefined; update the call site (where withTraceClient
supplies options) or inside GraphqlVtexContextFactory to guard extraction: if
options.OTEL is present use
OTELAPI.propagation.extract(OTELAPI.context.active(),
options.OTEL.__otelContext) otherwise call OTELAPI.propagation.extract with an
empty carrier (e.g., {}) so the non-instrumented path remains intact and tests
using plain Options continue to work. Ensure you modify the logic around
OTELAPI.propagation.extract and references to options.OTEL.__otelContext and
validate behavior in GraphqlVtexContextFactory and withTraceClient.

In `@packages/api/src/typings/globals.ts`:
- Line 21: The OTEL field on the Options type was widened to Record<string,
any>, losing the specific shape used elsewhere; restore a precise, optional OTEL
interface (e.g., declare an OTEL?: { __otelContext?: unknown; /* add only needed
fields */ } ) instead of Record<string, any>, and keep any defaulting/mandatory
logic in the options construction code (where Options instances are created) so
callers can rely on options.OTEL.__otelContext without casting; update the
Options type declaration (the OTEL symbol) and ensure the constructor or factory
that builds Options supplies defaults/validation for OTEL rather than broadening
the global type.

In `@packages/core/discovery.config.default.js`:
- Around line 166-170: The default config removed analytics.otelEnabled but
instrumentation initialization in instrumentation.ts still checks
config.analytics.otelEnabled === true; restore alignment by reintroducing
analytics.otelEnabled (set to true or the intended default) in the default
config object so the OTEL bootstrap guard in instrumentation.ts continues to
behave as expected, or alternatively update the guard in the initialize/boot
logic in instrumentation.ts to use the new runtime gate (e.g., check the new
feature flag or environment-derived value) and remove reliance on
analytics.otelEnabled; reference the analytics.otelEnabled key and the
initialization guard in instrumentation.ts when making the change.

In `@packages/core/next.config.js`:
- Line 17: The startup log currently prints a hardcoded "Analytics Enabled:
true" which can be false at runtime; update the log to reflect the actual
analytics flag by using the configuration value
(storeConfig.analytics?.otelEnabled or a derived const like analyticsEnabled)
instead of the literal true so the build output matches runtime telemetry state
and aids debugging.

In `@packages/core/src/server/options.ts`:
- Around line 55-68: Move OTEL setup (OTELAPI.trace.getTracer, tracer.startSpan,
OTELAPI.trace.setSpan and OTELAPI.propagation.inject) into the try block and
initialize the span variable to undefined before the try so the catch/finally
can always reference it; specifically, declare let span: ReturnType<typeof
tracer.startSpan> | undefined (or appropriate type) before the try, then inside
the try call getTracer(), startSpan(), setSpan(...) and inject(...), and return
options as T, while the catch uses span?.setStatus and span?.recordException and
the finally always calls span?.end().
- Around line 47-53: In withTraceClient update the options object to preserve
existing apiOptions.OTEL fields instead of overwriting them (merge
apiOptions.OTEL into OTEL so apiOptions.OTEL.enabled and other properties are
retained) and move the OTEL setup (calls to getTracer, startSpan, setSpan,
inject) inside the try block so any setup errors are caught and ensure the
finally block always ends/cleans the span; reference the options constant and
the functions getTracer, startSpan, setSpan, inject, and the try/catch/finally
surrounding the return.

In `@packages/diagnostics/`@types/global.d.ts:
- Around line 3-12: The global declaration still imports LogClient from the
removed `@vtex/diagnostics-nodejs` and declares TELEMETRY_CLIENT / TRACE_CLIENT
types that no longer match start.ts (which stores an OpenTelemetry SDK
instance). Remove the import line and update the types in the fsDiagnostics
global to match the actual runtime types used in
packages/diagnostics/src/start.ts (e.g., set TELEMETRY_CLIENT to the
OpenTelemetry SDK type you instantiate there — or use a conservative
unknown/any/NodeSDK type if you don’t want to add a new dependency — and replace
TRACE_CLIENT/LOGGER_CLIENT with the corresponding OpenTelemetry/opaque types or
undefined). Ensure you reference and mirror the exact symbol used in start.ts
for TELEMETRY_CLIENT and stop importing LogClient.

In `@packages/diagnostics/package.json`:
- Around line 24-27: The package-level "types" field is out of sync with the
exports map; update the package.json "types" entry (the top-level "types" key)
to point to "./dist/index.d.ts" so it matches exports["."].types, ensuring both
consumers using the export map and tools reading package.json resolve the same
declaration file.
- Around line 33-43: The package.json contains pinned versions for several
shared deps ("`@grpc/grpc-js`", "`@opentelemetry/api`", "`@opentelemetry/api-logs`",
"`@opentelemetry/exporter-logs-otlp-grpc`",
"`@opentelemetry/exporter-trace-otlp-grpc`",
"`@opentelemetry/instrumentation-http`", "`@opentelemetry/resources`",
"`@opentelemetry/sdk-logs`", "`@opentelemetry/sdk-node`",
"`@opentelemetry/sdk-trace-node`", "`@vtex/diagnostics-semconv`") — move each of
these entries into the workspace catalog in pnpm-workspace.yaml (or the repo’s
catalog file) with the desired version, then replace the inline versions in this
package.json with catalog references (e.g. "catalog:") so the package.json uses
the catalog alias for each dependency.

In `@packages/diagnostics/src/logger.ts`:
- Around line 24-37: setupLogs() currently constructs a LoggerProvider (new
LoggerProvider(...)) and installs it via
logs.setGlobalLoggerProvider(loggerProvider) but never returns or exposes it, so
its buffered BatchLogRecordProcessor can be dropped on exit; modify setupLogs()
to return the created loggerProvider (or a dedicated async shutdown function)
and update the SIGTERM handler in start.ts to await loggerProvider.shutdown()
(alongside awaiting sdk.shutdown()) so buffered log records are flushed before
process exit; reference symbols: setupLogs(), LoggerProvider,
BatchLogRecordProcessor, logs.setGlobalLoggerProvider,
loggerProvider.shutdown(), and the SIGTERM handler that calls sdk.shutdown().

In `@packages/diagnostics/src/start.ts`:
- Around line 18-24: The resource built by resourceFromAttributes is missing the
OTel "service.name" attribute; include the bootstrap's serviceName into that
attributes object (e.g., add ['service.name']: serviceName ?? opt.serviceName ??
'unknown_service') so the resource created in the resourceFromAttributes call
contains the proper service identifier; update the resource construction in
start.ts (the resourceFromAttributes invocation) to include this key while
keeping existing attributes like ATTR_VTEX_ACCOUNT_NAME unchanged.
- Around line 36-48: Move the assignment to the cached singleton so it only
happens after sdk.start() completes successfully: don't set
global.fsDiagnostics.TELEMETRY_CLIENT before calling sdk.start(); call
sdk.start(), let it complete (catch synchronous throws), and only then assign
global.fsDiagnostics.TELEMETRY_CLIENT = sdk so a thrown error from sdk.start()
won't leave a broken singleton; update the shutdown handler to reference the
cached TELEMETRY_CLIENT (or sdk) as appropriate and ensure exceptions from
sdk.start() are propagated/handled without mutating
global.fsDiagnostics.TELEMETRY_CLIENT.

---

Nitpick comments:
In `@packages/core/test/server/index.test.ts`:
- Around line 21-29: The mock for trace.setSpan used in tests should return a
stable context object so withTraceClient() passes a real value into
propagation.inject(); update the mock implementation referenced as setSpan (and
any usages in withTraceClient() test setup) to return a consistent object (e.g.,
an empty context {} or a named mockContext) and ensure propagation.inject is
called with that returned object instead of undefined.

In `@packages/diagnostics/configs/prod.json`:
- Around line 4-8: The prod config raised the global sampling from 1% to 30%
(defaultRate and the "trace_all" rule's sampleRate both set to 0.3), which will
massively increase ingest/cost; revert defaultRate and the "trace_all"
sampleRate back to 0.01 (1%) or gate the 0.3 change behind a feature
flag/gradual rollout, and add instrumentation and alerts for exporter failures,
queue pressure, and ingest cost before enabling the higher rate cluster-wide;
ensure the fix updates the JSON entries for "defaultRate" and the rule named
"trace_all" and document the rollout plan.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b406e425-b6fd-425a-a705-f929ee67ea90

📥 Commits

Reviewing files that changed from the base of the PR and between 649b754 and 9ce92d1.

⛔ Files ignored due to path filters (2)
  • docs/observability.md is excluded by none and included by none
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (17)
  • packages/api/src/observability/telemetry.ts
  • packages/api/src/platforms/vtex/index.ts
  • packages/api/src/typings/globals.ts
  • packages/core/discovery.config.default.js
  • packages/core/next.config.js
  • packages/core/src/instrumentation.ts
  • packages/core/src/server/options.ts
  • packages/core/test/server/index.test.ts
  • packages/diagnostics/@types/global.d.ts
  • packages/diagnostics/configs/prod.json
  • packages/diagnostics/package.json
  • packages/diagnostics/src/globals.ts
  • packages/diagnostics/src/index.ts
  • packages/diagnostics/src/logger.ts
  • packages/diagnostics/src/start.ts
  • packages/diagnostics/src/tracer.ts
  • packages/diagnostics/vite.config.mts

Comment thread packages/api/src/typings/globals.ts Resolved
Comment thread packages/diagnostics/package.json Resolved
Comment thread packages/diagnostics/package.json Resolved
Comment thread packages/diagnostics/src/logger.ts Resolved
Comment thread packages/diagnostics/src/start.ts Resolved
Comment thread packages/diagnostics/src/start.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/core/src/instrumentation.ts (1)

5-17: ⚠️ Potential issue | 🔴 Critical

Restore analytics.otelEnabled opt-out for OTEL bootstrap in Next instrumentation

  • packages/core/src/instrumentation.ts register() initializes telemetry whenever process.env.NEXT_RUNTIME === 'nodejs', calling getTelemetryClient(...) without checking config.analytics?.otelEnabled.
  • packages/diagnostics/src/start.ts getTelemetryClient() starts the NodeSDK via sdk.start() unconditionally (aside from reusing an existing global client).
  • Repo-wide usage of otelEnabled is limited to packages/core/src/server/options.ts (apiOptions.OTEL.enabled) and docs, so analytics.otelEnabled: false appears to be bypassed for the Next.js instrumentation hook.
    Action: reintroduce gating in register() (or ensure @faststore/diagnostics respects an enabled flag) so the opt-out contract matches configuration/docs.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/instrumentation.ts` around lines 5 - 17, In register() in
instrumentation.ts, avoid unconditionally calling getTelemetryClient(...) when
NEXT_RUNTIME==='nodejs'; instead gate the telemetry bootstrap with the analytics
opt-out by checking config.analytics?.otelEnabled (treat undefined as enabled,
but respect false) before importing/calling getTelemetryClient, or alternatively
pass an explicit enabled flag through to getTelemetryClient so
packages/diagnostics (start.ts / NodeSDK start) can no-op when otel is disabled;
update the conditional around the import/return that currently calls
getTelemetryClient to honor config.analytics?.otelEnabled.
♻️ Duplicate comments (1)
packages/api/src/observability/telemetry.ts (1)

54-74: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

End resolver spans on rejection and sync throw paths.

The resolver span is closed on success but not on error, so rejected async resolvers and thrown sync resolvers leave spans open.

Suggested fix
       if (returnedValue instanceof Promise) {
         return returnedValue
-          .then((promisedResult) => {
-            span?.end()
-
-            return promisedResult
-          })
+          .then((promisedResult) => promisedResult)
           .catch((err) => {
             throw catchError(
               err,
               span,
               resolverName ?? 'Unknown Graphql Resolver'
             )
+          })
+          .finally(() => {
+            span?.end()
           }) as TReturn
       }

       span?.end()
       return returnedValue
     } catch (error: any) {
-      throw catchError(error, span, resolverName)
+      const handled = catchError(error, span, resolverName)
+      span?.end()
+      throw handled
     }
#!/bin/bash
set -euo pipefail
rg -n -C4 'returnedValue instanceof Promise|catchError\\(|span\\?\\.end\\(|\\.finally\\(' packages/api/src/observability/telemetry.ts

Expected result: every resolver execution path (sync success, sync throw, async resolve, async reject) should include one span end.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/api/src/observability/telemetry.ts` around lines 54 - 74, The
resolver span isn't ended on error paths: add span?.end() before rethrowing in
both the async rejection and sync throw paths so every execution ends the span;
specifically, update the Promise branch around returnedValue (either call
span?.end() in the .catch before calling throw catchError(...) or replace the
.then/.catch with .finally to call span?.end()) and ensure the outer catch block
that catches synchronous throws calls span?.end() before throwing
catchError(error, resolverName). Reference returnedValue, span, catchError, and
resolverName when making the changes.
🧹 Nitpick comments (1)
packages/api/test/unit/platforms/vtex/clients/commerce.test.ts (1)

18-19: ⚡ Quick win

Use an explicit OTEL fixture shape in this unit test.

OTEL: {} is too loose versus runtime wiring and can hide contract-shape regressions in context factories.

Suggested refactor
-  OTEL: {},
+  OTEL: {
+    enabled: false,
+    __otelContext: {},
+  },

As per coding guidelines, for packages/**/*.{ts,tsx}: "Ensure type safety and avoid type assertions when possible."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/api/test/unit/platforms/vtex/clients/commerce.test.ts` around lines
18 - 19, The test uses a loose OTEL: {} fixture which can hide contract
regressions; update the test to construct an explicit OTEL fixture matching the
runtime shape and type rather than an empty object or unsafe assertion. Import
or reference the Options/type used by the code under test and replace OTEL: {}
with a well-typed object containing the expected OTEL properties (e.g., the
fields the context factory expects), ensuring the fixture aligns with the
Options interface and removing the need for a broad type assertion.

Sources: Coding guidelines, Pipeline failures

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@packages/core/src/instrumentation.ts`:
- Around line 5-17: In register() in instrumentation.ts, avoid unconditionally
calling getTelemetryClient(...) when NEXT_RUNTIME==='nodejs'; instead gate the
telemetry bootstrap with the analytics opt-out by checking
config.analytics?.otelEnabled (treat undefined as enabled, but respect false)
before importing/calling getTelemetryClient, or alternatively pass an explicit
enabled flag through to getTelemetryClient so packages/diagnostics (start.ts /
NodeSDK start) can no-op when otel is disabled; update the conditional around
the import/return that currently calls getTelemetryClient to honor
config.analytics?.otelEnabled.

---

Duplicate comments:
In `@packages/api/src/observability/telemetry.ts`:
- Around line 54-74: The resolver span isn't ended on error paths: add
span?.end() before rethrowing in both the async rejection and sync throw paths
so every execution ends the span; specifically, update the Promise branch around
returnedValue (either call span?.end() in the .catch before calling throw
catchError(...) or replace the .then/.catch with .finally to call span?.end())
and ensure the outer catch block that catches synchronous throws calls
span?.end() before throwing catchError(error, resolverName). Reference
returnedValue, span, catchError, and resolverName when making the changes.

---

Nitpick comments:
In `@packages/api/test/unit/platforms/vtex/clients/commerce.test.ts`:
- Around line 18-19: The test uses a loose OTEL: {} fixture which can hide
contract regressions; update the test to construct an explicit OTEL fixture
matching the runtime shape and type rather than an empty object or unsafe
assertion. Import or reference the Options/type used by the code under test and
replace OTEL: {} with a well-typed object containing the expected OTEL
properties (e.g., the fields the context factory expects), ensuring the fixture
aligns with the Options interface and removing the need for a broad type
assertion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3c31f678-0cbe-4558-8dee-c5674b02dd63

📥 Commits

Reviewing files that changed from the base of the PR and between 9ce92d1 and 811b131.

📒 Files selected for processing (6)
  • packages/api/src/observability/telemetry.ts
  • packages/api/test/unit/platforms/vtex/clients/commerce.test.ts
  • packages/core/src/instrumentation.ts
  • packages/diagnostics/package.json
  • packages/diagnostics/src/logger.ts
  • packages/diagnostics/src/start.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/diagnostics/src/logger.ts
  • packages/diagnostics/src/start.ts
  • packages/diagnostics/package.json

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/api/test/integration/mutations.test.ts`:
- Line 27: The test adds a new showSponsored field that looks unrelated to the
OpenTelemetry migration; either remove this field from the test to keep the PR
focused, or if it is intentional, update the Options shape/type (e.g., the
Options interface/contract used by your mutations and fixtures) and all
callers/mocks (tests that construct Options in mutations.test.ts and any
factories) to include showSponsored, adjust affected tests, and add a note in
the PR description explaining the intentional contract change so reviewers know
it’s deliberate rather than incidental.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2bebabbe-d4c7-493f-bfcf-045474bf0211

📥 Commits

Reviewing files that changed from the base of the PR and between 811b131 and a3da4cd.

📒 Files selected for processing (3)
  • packages/api/test/integration/mutations.test.ts
  • packages/api/test/integration/queries.test.ts
  • packages/api/test/mocks/ValidateCartMutation.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/api/test/integration/queries.test.ts
  • packages/api/test/mocks/ValidateCartMutation.ts

@renatomaurovtex renatomaurovtex left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — feat: removing vtex/diagnostics-nodejs

Migrating @faststore/diagnostics off @vtex/diagnostics-nodejs onto raw OpenTelemetry SDKs. You own this area, so the architecture direction isn't in question — flagging the concrete things that look like they'd bite on build/behavior. The body reads like a spike ("Testing OTEL…"); calling that out in case this isn't meant to merge as-is. Reviewed everything except pnpm-lock.yaml.


🔴 build/types packages/diagnostics/@types/global.d.ts still imports from the removed package

package.json drops @vtex/diagnostics-nodejs from dependencies, but the global type still imports deep paths from it:

import type { TelemetryClient } from '@vtex/diagnostics-nodejs/dist/telemetry/client.js'
import type { TraceClient } from '@vtex/diagnostics-nodejs/dist/types/traces.js'
import type { LogClient } from '@vtex/diagnostics-nodejs/dist/types/logs.d.ts'

With the dep gone these imports resolve only by accident (transitive hoist) and break tsc otherwise. On top of that the declared shapes no longer match what's assigned at runtime:

  • TELEMETRY_CLIENT: TelemetryClient ← assigned a NodeSDK (start.ts)
  • LOGGER_CLIENT: LogClient ← assigned a LoggerProvider (logger.ts)
  • TRACE_CLIENT: TraceClient ← never assigned anymore

Suggest retyping the global to the actual OTEL types you now store (NodeSDK, LoggerProvider) and dropping the dead TRACE_CLIENT.

🔴 deps New runtime deps on a published package need the discipline checklist + sign-off

@faststore/diagnostics is published (4.3.0-dev.2, no private: true, ships dist). This adds 8 runtime deps (@grpc/grpc-js, @opentelemetry/sdk-node, sdk-logs, sdk-trace-node, exporter-*-otlp-grpc, api-logs, resources) and swaps @vtex/diagnostics-nodejs→@vtex/diagnostics-semconv. Per Dependency Discipline these need bucket/justification/bundle-impact recorded and explicit human approval in the PR description. Shared versions should come from catalog: in pnpm-workspace.yaml rather than fresh ^ ranges — note the OTEL set is also version-skewed (api-logs/exporter-* on 0.219.0, sdk-trace-node/resources on 2.8.0).

🟠 behavior OTEL opt-out is removed — telemetry is now always-on

instrumentation.ts drops the config.analytics.otelEnabled === true gate, next.config.js hardcodes Analytics Enabled: true, and otelEnabled is removed from discovery.config.default.js. Combined with the hardcoded *.vtex.systems collector endpoints in globals.ts, every FastStore store (this is MIT/open-source) now ships traces+logs to VTEX collectors with no way to disable it. Is removing the toggle intentional? At minimum this deserves a release note.

🟠 bug withTraceClient try/catch wraps a no-op and can return undefined

const context = OTELAPI.trace.setSpan(OTELAPI.context.active(), span)
OTELAPI.propagation.inject(context, options.OTEL.__otelContext) // real work, OUTSIDE try
try {
  return options as T            // nothing here can throw
} catch (error) {                // dead branch — and it doesn't return,
  span?.setStatus(...)           // so on a (impossible) throw the fn returns undefined,
  span?.recordException(error)   // violating Promise<T>
} finally {
  span?.end()                    // span ends immediately around a bare return
}

The span starts and ends around a return statement, so it traces nothing and the child resolver spans (extracted via propagation) attach to an already-ended parent. If the intent is a parent span over the GraphQL execution, the inject + the actual execution need to be inside the traced scope; otherwise drop the try/catch and just return options.

🟡 type OTEL public type loosened to Record<string, any>

packages/api/src/typings/globals.ts changes the typed OTEL?: { enabled; traceparent?; tracestate? } to OTEL: Record<string, any> (also now required). That's a public Options contract change and an any regression — downstream callers lose all type safety on OTEL. Consider a named interface ({ __otelContext: Record<string, unknown>; enabled?: boolean }).

🟡 nit compression: 'gzip' as any in tracer.ts — cast hides a typing gap; prefer the exporter's CompressionAlgorithm enum.

💬 config prod sampling bumped 0.01 → 0.3 (30×)

configs/prod.json raises defaultRate 30×. Just confirming that trace-volume/cost jump is intended for prod.

💬 scope Unrelated showSponsored changes in the diff?

test/integration/mutations.test.ts gains showSponsored: false and test/mocks/ValidateCartMutation.ts adds showSponsored=false to the IS URL — these look unrelated to the OTEL migration. Should they be in this PR?


Verdict: Changes requested

Blocking (🔴/🟠):

  • @types/global.d.ts imports a removed package and its declared types no longer match the assigned values — retype to the OTEL types you now store.
  • Published-package runtime dep swap needs the Dependency Discipline checklist + explicit human sign-off; align versions via catalog:.
  • Confirm the removal of the OTEL opt-out (always-on telemetry to VTEX collectors) is intentional; release-note it.
  • withTraceClient try/catch wraps a no-op and can return undefined — fix the traced scope or drop the wrapper.

Non-blocking (🟡/💬):

  • OTEL: Record<string, any> public-type regression.
  • 'gzip' as any cast.
  • Confirm the 30× prod sampling bump.
  • Drop the unrelated showSponsored test changes (or explain why they belong here).

Checks to confirm before merge: pnpm lint · build (tsc on diagnostics/api/core) · pnpm turbo run test --filter=@faststore/api --filter=@faststore/core · pnpm size.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/server/index.ts`:
- Around line 138-151: The type assertion in the destructuring of the result
from the run() function incorrectly marks errors as a required field. Change the
type assertion from `{ data: D; errors: unknown[] }` to `{ data: D; errors?:
unknown[] }` to make the errors field optional, matching what the enveloped
GraphQL execute function can actually return. Then ensure the function's return
type contract is satisfied by defaulting errors to an empty array when it is
undefined, using the nullish coalescing operator or conditional logic when
assigning to the errors field in the returned object.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: db10420d-7c33-4fad-92cb-c7a452e49615

📥 Commits

Reviewing files that changed from the base of the PR and between a3da4cd and 0ac3dcd.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (6)
  • packages/api/src/observability/telemetry.ts
  • packages/core/src/server/index.ts
  • packages/core/src/server/options.ts
  • packages/diagnostics/@types/global.d.ts
  • packages/diagnostics/package.json
  • packages/diagnostics/src/globals.ts
💤 Files with no reviewable changes (1)
  • packages/diagnostics/src/globals.ts

Comment thread packages/core/src/server/index.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/diagnostics/src/logger.ts`:
- Around line 97-101: The ATTR_VTEX_APPLICATION_ID attribute in the attributes
object is hardcoded to 'faststore' instead of using the opt.serviceName value
like start.ts does, causing log and trace correlation issues. Replace the
hardcoded 'faststore' value for ATTR_VTEX_APPLICATION_ID with opt.serviceName to
ensure consistency across the telemetry attributes and maintain proper
correlation between logs and traces.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: afcbe222-3f45-42dd-b11b-3f3f3398446c

📥 Commits

Reviewing files that changed from the base of the PR and between 0ac3dcd and a28c86b.

📒 Files selected for processing (2)
  • packages/diagnostics/src/logger.ts
  • packages/diagnostics/src/start.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/diagnostics/src/start.ts

Comment thread packages/diagnostics/src/logger.ts Resolved
@ommeirelles
ommeirelles dismissed renatomaurovtex’s stale review July 21, 2026 18:48

Requested new review after changes

Comment thread packages/core/src/pages/api/graphql.ts Resolved
Comment thread packages/core/next.config.js Outdated
Root folder at: ${getRootFolder()}
AccountID: ${storeConfig.api?.storeId ?? 'Unknown'}
Analytics Enabled: ${storeConfig.analytics?.otelEnabled ?? false}
Analytics Enabled: true

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be always true?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is the default behaviour. This shouldn't be disabled anymore after discussing with the team

@eduardoformiga

Copy link
Copy Markdown
Member

a IA recomendou algumas coisas, vê se faz sentido ou podemos skipar:

Resultado concreto em produção: um console.info("OTEL logger is disabled...") por request de GraphQL (o BFF inteiro), mais o custo de montar aquela string de debug com JSON.stringify(variables) a cada chamada. Ou seja, não é "nada" — é ruído de log no hot path do BFF.

E tem um agravante que faz isso valer para dev também: o const OTELLogger = logger(getOTELLogger(...)) é avaliado no import do módulo, antes de qualquer getTelemetryClient rodar. Então o client fica capturado como undefined em qualquer ambiente → a feature de log nunca emite e sempre spama.

Ponto secundário e mais leve: o span raiz no execute() (server/index.ts) também não está atrás de flag — ele sempre cria/encerra span. Em prod é inofensivo porque, sem o SDK iniciado, o getTracer devolve um tracer no-op. Baixo risco, mas não é "desligado por flag", é "desligado porque o SDK não sobe".

Minha recomendação antes do merge/release
Barato e vale muito (para a premissa de zero-impacto realmente valer):

Silenciar o spam do logger(undefined) (não logar a cada chamada — ou warn-once, ou simplesmente não logar).
Tirar/guardar o OTELLogger('info', ...JSON.stringify(request)) — além do spam, serializar o request inteiro vaza headers/cookies/tokens no log.

Looks like SonarQube is complaining. Can you take a look?
Screenshot 2026-07-29 at 20 03 45

@renatomaurovtex renatomaurovtex left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up review — feat: removing vtex/diagnostics-nodejs

Re-reviewed after the 3 commits pushed today (b56804d, a198e2d, e1c088f) since my June 14 review was dismissed. Checked each blocking point from that review against the current head.

Previously 🔴/🟠, now resolved:

  • @types/global.d.ts no longer imports the removed package — retyped to NodeSDK, dead TRACE_CLIENT/TELEMETRY_CLIENTS map dropped.
  • withTraceClient (the no-op try/catch that traced nothing) is gone entirely — server/index.ts now wraps execution in a real withRootSpan that's active-context-aware and only runs when OTEL_ENABLED.
  • Always-on telemetry: instrumentation.ts now hardcodes instrumentationEnabled = false ("Disabled feature until release date"), and apiOptions.OTEL_ENABLED = false. Telemetry is fully opt-in/gated pending release rather than always-on — addresses the concern in the safer direction. Confirmed with @ommeirelles's comment that the toggle removal itself was discussed with the team.
  • OTEL: Record<string, any> public-type regression — replaced with a typed OTEL_ENABLED?: boolean, no more any.
  • 'gzip' as any cast — gone; compression now follows the standard OTEL_EXPORTER_OTLP_COMPRESSION env var.
  • Sensitive-data logging (flagged by @eduardoformiga's AI-assisted pass on 07-29: JSON.stringify(request) in the OTEL logger leaking headers/cookies/tokens) — fixed in e1c088f. Current graphql.ts only logs operation.__meta__.operationName/operationHash, with an explicit comment that variables/query body are deliberately excluded. Also fixed the related "logger spams on every request even when disabled" bug: logger() now resolves TELEMETRY_CLIENT per-call instead of capturing it at module-load time (undefined forever) — covered by a new regression test in logger.test.ts.

Still open:

  • 🟠 deps — this still adds 8 new OTEL runtime deps (@opentelemetry/sdk-node, sdk-logs, sdk-trace-node, exporter-*-otlp-grpc, api-logs, resources, @grpc/grpc-js) to @faststore/diagnostics, a published package. Per Dependency Discipline this needs the bucket/justification/bundle-impact checklist and an explicit human sign-off recorded in the PR description — the body still just says "Testing OTEL without @vtex/diagnostics-nodejs". Given telemetry is now hard-disabled until release, this isn't merge-blocking today, but flagging so it's not missed before the flag flips on.
  • 🟡 SonarQube quality gate is failing: 43.10% coverage on new code (needs 75%). Rest of CI (build, FastStore, codesandbox, PR title) is green; UI Tests pending Chromatic baseline acceptance only.
  • 💬 showSponsored: false in mutations.test.ts still looks unrelated to this PR — same note as before, not blocking.

Verdict: Approved with comments

Blocking (🔴/🟠): none for the current disabled-by-default state. Confirm before flipping the feature flag on for release: (1) Dependency Discipline sign-off recorded in the PR description for the new OTEL runtime deps, (2) new-code coverage above the Sonar gate.

Non-blocking (🟡/💬):

  • SonarQube new-code coverage gate (43.10% < 75%).
  • Unrelated showSponsored test change.

Checks to confirm before merge: pnpm lint · build · pnpm turbo run test --filter=@faststore/diagnostics --filter=@faststore/api --filter=@faststore/core · pnpm size.

@sonar-workflows

Copy link
Copy Markdown

@ommeirelles
ommeirelles merged commit 74e2d50 into dev Aug 11, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants