Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
b06954f
fix(telemetry): align session lifecycle with OTel
zjunothing Aug 6, 2026
e774bb6
Merge branch 'main' into fix/issue-8589-otel-session-lifecycle
wenshao Aug 6, 2026
5b9c8c6
feat(telemetry): complete session lifecycle coverage
zjunothing Aug 6, 2026
716b243
Merge branch 'main' into fix/issue-8589-otel-session-lifecycle
wenshao Aug 6, 2026
babe9db
fix(telemetry): deduplicate deferred session starts
zjunothing Aug 7, 2026
0588bf9
test(telemetry): cover duplicate session starts
zjunothing Aug 7, 2026
aba197f
fix(serve): emit daemon session starts
zjunothing Aug 7, 2026
8cbb1ed
Merge branch 'main' into fix/issue-8589-otel-session-lifecycle
qwen-code-dev-bot Aug 7, 2026
8274e0c
fix(telemetry): repair session lifecycle test wiring and record attri…
qwen-code-dev-bot Aug 7, 2026
cdfaea1
Merge branch 'main' into fix/issue-8589-otel-session-lifecycle
qwen-code-dev-bot Aug 8, 2026
05859b8
fix(telemetry): skip session lifecycle transition on same-id resume (…
qwen-code-dev-bot Aug 8, 2026
946b27a
Merge branch 'main' into fix/issue-8589-otel-session-lifecycle
qwen-code-dev-bot Aug 8, 2026
95e2b18
test(telemetry): pin session lifecycle behaviors per review (#8616)
qwen-code-dev-bot Aug 8, 2026
7e30622
Merge branch 'main' into fix/issue-8589-otel-session-lifecycle
qwen-code-dev-bot Aug 8, 2026
2ac0d47
fix(telemetry): emit session start catch-up on every init path (#8616)
qwen-code-dev-bot Aug 8, 2026
2b160e0
Merge branch 'main' into fix/issue-8589-otel-session-lifecycle
qwen-code-dev-bot Aug 8, 2026
33916e2
Merge remote-tracking branch 'origin/main' into fix/issue-8589-otel-s…
qwen-code-dev-bot Aug 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions docs/design/otel-session-lifecycle-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# OpenTelemetry Session Lifecycle

## Status

Implemented in issue #8589.

## Scope

Qwen Code already records the application session ID as `session.id` and maps
it to `gen_ai.conversation.id` on GenAI LLM and agent spans. This design adds
the OpenTelemetry General Session lifecycle events without removing the
existing Qwen-specific telemetry fields or event names.

The implementation follows the Development-status General Session semantic
conventions at:

<https://opentelemetry.io/docs/specs/semconv/general/session/>

The GenAI conversation mapping follows:

<https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-agent-spans.md>

## Event representation

The standard lifecycle events are emitted as OpenTelemetry LogRecords with
the required `event.name` attribute:

| Event | Required attributes | Emission point |
| --------------- | ------------------- | -------------------------------------------------------- |
| `session.start` | `session.id` | Initial `Config` initialization and every session switch |
| `session.end` | `session.id` | Session switch and telemetry shutdown |

The existing `qwen-code.config` / `cli_config` and RUM `session_start` events
remain unchanged for backward compatibility. The standard records are
additive and are emitted through the configured OpenTelemetry logs pipeline.

## Session continuation

`Config.startNewSession()` is used for both replacing the current conversation
(`/clear`, `/new`) and resuming a persisted conversation. A persisted
`sessionData` argument identifies the latter continuation case. On a
continuation, the new `session.start` record includes
`session.previous_id`; replacement sessions do not claim continuation.

The outgoing session is ended before the new session starts. Telemetry
shutdown ends the currently active session before shutting down the SDK.

## Compatibility and safety

- `session.id` remains on existing spans and logs.
- `gen_ai.conversation.id` remains the session correlation field for GenAI
spans.
- `session.previous_id` is emitted only when the application has an explicit
persisted continuation, and it is never equal to the new `session.id`.
- Session event emission is best-effort through the existing OTel logger and
does not block session switching or shutdown.
11 changes: 11 additions & 0 deletions docs/developers/development/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -858,6 +858,17 @@ The daemon process (long-running HTTP server mode) exposes its own metrics.

Distributed tracing spans form a tree rooted at `qwen-code.interaction`. Each interaction is a trace root with its own `traceId`; cross-prompt correlation uses the `session.id` attribute.

Session lifecycle is also exported through the OpenTelemetry General Session
semantic conventions. When the OTel logs pipeline is enabled, Qwen Code emits
`session.start` and `session.end` log events with the required `session.id`
attribute. A resumed persisted conversation includes `session.previous_id` on
its `session.start` event. `/clear` and other replacement flows intentionally
do not claim continuation because they discard the previous conversation.

The existing Qwen-specific `qwen-code.config`/`cli_config` and
`end_session` records remain available for compatibility. GenAI request spans
continue to use `gen_ai.conversation.id` for the same owning session ID.

- `qwen-code.interaction`: Root span for each user prompt turn.
- **Attributes**: `session.id`, optional ARMS extension `gen_ai.user.id`, `qwen-code.prompt_id`, `qwen-code.message_type`, `qwen-code.model`, `qwen-code.approval_mode`, `interaction.sequence`, `interaction.duration_ms`, `qwen-code.turn_status` ("ok"/"error"/"cancelled")

Expand Down
25 changes: 25 additions & 0 deletions packages/core/src/config/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
isTelemetrySdkInitialized,
shutdownTelemetry,
refreshSessionContext,
logStartSession,
} from '../telemetry/index.js';
import type {
ContentGenerator,
Expand Down Expand Up @@ -326,6 +327,7 @@ vi.mock('../telemetry/loggers.js', async (importOriginal) => {
return {
...actual,
logRipgrepFallback: vi.fn(),
logStartSession: vi.fn(actual.logStartSession),
};
});

Expand Down Expand Up @@ -2232,6 +2234,29 @@ describe('Server Config (config.ts)', () => {
});

describe('startNewSession', () => {
it('does not self-link a resumed session when the id is unchanged', async () => {
const sessionId = 'same-session-id';
const config = new Config({ ...baseParams, sessionId });
await config.initialize({
skipGeminiInitialization: true,
skipHooks: true,
skipMcpDiscovery: true,
skipSkillManager: true,
skipFileCheckpointing: true,
});
vi.mocked(logStartSession).mockClear();

config.startNewSession(sessionId, {
conversation: { messages: [] },
} as unknown as ResumedSessionData);

expect(logStartSession).toHaveBeenCalledWith(
config,
expect.anything(),
undefined,
);
});

it('rejects a session switch while the current recorder owns the writer lease', () => {
const config = new Config({ ...baseParams, chatRecording: true });
const originalSessionId = config.getSessionId();
Expand Down
10 changes: 9 additions & 1 deletion packages/core/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ import {
shutdownTelemetry,
refreshSessionContext,
logStartSession,
logSessionEnd,
logRipgrepFallback,
RipgrepFallbackEvent,
StartSessionEvent,
Expand Down Expand Up @@ -3794,6 +3795,7 @@ export class Config {
});

const previousSessionId = this.sessionId;
logSessionEnd(this);
this.sessionId = sessionId ?? randomUUID();
// Unconditional: startNewSession is only called on the canonical Config
// instance (the one that already claimed via sessionEnvClaimed), so this
Expand Down Expand Up @@ -3840,7 +3842,13 @@ export class Config {
// one, and the "N-shotted" PR label would span sessions.
CommitAttributionService.resetInstance();
if (this.initialized) {
logStartSession(this, new StartSessionEvent(this));
logStartSession(
this,
new StartSessionEvent(this),
sessionData && previousSessionId !== this.sessionId
? previousSessionId
: undefined,
);
}

// Refresh the runtime.json sidecar so external observers (terminal
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/telemetry/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export const EVENT_API_ERROR = 'qwen-code.api_error';
export const EVENT_API_CANCEL = 'qwen-code.api_cancel';
export const EVENT_API_RESPONSE = 'qwen-code.api_response';
export const EVENT_CLI_CONFIG = 'qwen-code.config';
export const EVENT_SESSION_START = 'session.start';
export const EVENT_SESSION_END = 'session.end';
export const EVENT_EXTENSION_DISABLE = 'qwen-code.extension_disable';
export const EVENT_EXTENSION_ENABLE = 'qwen-code.extension_enable';
export const EVENT_EXTENSION_INSTALL = 'qwen-code.extension_install';
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/telemetry/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export {
} from './config.js';
export {
logStartSession,
logSessionEnd,
logUserPrompt,
logUserRetry,
logToolCall,
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/telemetry/loggers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ import { recordTokenUsageFromApiResponseBestEffort } from '../services/tokenUsag
import { isChatRecordingSuppressed } from '../utils/chat-recording-suppression-context.js';
import { ToolErrorType } from '../tools/tool-error.js';
import { createDebugLogger } from '../utils/debugLogger.js';
import { emitSessionEnd, emitSessionStart } from './session-events.js';

const shouldLogUserPrompts = (config: Config): boolean =>
config.getTelemetryLogPromptsEnabled();
Expand Down Expand Up @@ -201,6 +202,7 @@ function runToolTelemetrySink(sink: () => void): void {
export function logStartSession(
config: Config,
event: StartSessionEvent,
previousSessionId?: string,
): void {
QwenLogger.getInstance(config)?.logStartSessionEvent(event);
if (!isTelemetrySdkInitialized()) return;
Expand Down Expand Up @@ -235,6 +237,12 @@ export function logStartSession(
attributes,
};
logger.emit(logRecord);
emitSessionStart(config.getSessionId(), previousSessionId);
}

export function logSessionEnd(config: Config): void {
if (!isTelemetrySdkInitialized()) return;
emitSessionEnd(config.getSessionId());
}

export function logUserPrompt(config: Config, event: UserPromptEvent): void {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/telemetry/runtime-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface TelemetryRuntimeConfig {
getTelemetryResourceAttributeWarnings(): readonly string[];
getCliVersion(): string | undefined;
getSessionId(): string;
isTelemetryInitializationDeferred?(): boolean;
isInteractive(): boolean;
getOutboundCorrelationPropagateTraceContext(): boolean;
}
16 changes: 16 additions & 0 deletions packages/core/src/telemetry/sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ vi.mock('@opentelemetry/instrumentation-http');
vi.mock('@opentelemetry/instrumentation-undici');
vi.mock('./gcp-exporters.js');
vi.mock('./log-to-span-processor.js');
vi.mock('./session-events.js', () => ({
emitSessionEnd: vi.fn(),
emitSessionStart: vi.fn(),
}));
vi.mock('./session-context.js');
vi.mock('./trace-context.js');
vi.mock('./tracer.js', () => ({
Expand All @@ -66,6 +70,7 @@ import { LogToSpanProcessor } from './log-to-span-processor.js';
import { setSessionContext } from './session-context.js';
import { setShellTracePropagation } from './trace-context.js';
import { createSessionRootContext } from './tracer.js';
import { emitSessionStart } from './session-events.js';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';

Expand Down Expand Up @@ -190,6 +195,17 @@ describe('Telemetry SDK', () => {
expect(NodeSDK.prototype.start).toHaveBeenCalledTimes(1);
});

it('emits the initial session start after deferred telemetry initialization', async () => {
const deferredConfig = {
...mockConfig,
isTelemetryInitializationDeferred: () => true,
} as unknown as Config;

await initializeTelemetry(deferredConfig);

expect(emitSessionStart).toHaveBeenCalledWith('test-session');
});

it('clears the in-flight promise so a failed init can be retried', async () => {
vi.mocked(NodeSDK.prototype.start).mockImplementationOnce(() => {
throw new Error('start failed');
Expand Down
10 changes: 9 additions & 1 deletion packages/core/src/telemetry/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ import type { TelemetryRuntimeConfig } from './runtime-config.js';
import { initializeMetrics } from './metrics.js';
import { createDebugLogger } from '../utils/debugLogger.js';
import { createSessionRootContext } from './tracer.js';
import { setSessionContext } from './session-context.js';
import { getCurrentSessionId, setSessionContext } from './session-context.js';
import { setShellTracePropagation } from './trace-context.js';
import { endInteractionSpan } from './session-tracing.js';
import { emitSessionEnd, emitSessionStart } from './session-events.js';

function createTelemetryDiagLogger(): DiagLogger {
const debugLogger = createDebugLogger('OTEL');
Expand Down Expand Up @@ -88,6 +89,9 @@ export function initializeTelemetry(
activeMetricReader = started.metricReader;
const sessionId = config.getSessionId();
setSessionContext(createSessionRootContext(sessionId), sessionId);
if (config.isTelemetryInitializationDeferred?.()) {
emitSessionStart(sessionId);
}
setShellTracePropagation(
config.getOutboundCorrelationPropagateTraceContext(),
);
Expand Down Expand Up @@ -140,6 +144,10 @@ export function shutdownTelemetry(): Promise<void> {
return;
}
endInteractionSpan('cancelled');
const currentSessionId = getCurrentSessionId();
if (currentSessionId) {
emitSessionEnd(currentSessionId);
}
const currentSdk = sdk;
const debugLogger = createDebugLogger('OTEL');
let timer: ReturnType<typeof setTimeout> | undefined;
Expand Down
55 changes: 55 additions & 0 deletions packages/core/src/telemetry/session-events.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import { logs } from '@opentelemetry/api-logs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { emitSessionEnd, emitSessionStart } from './session-events.js';

describe('session lifecycle events', () => {
const emit = vi.fn();

beforeEach(() => {
emit.mockReset();
vi.spyOn(logs, 'getLogger').mockReturnValue({ emit } as never);
});

it('emits the required attributes for session.start', () => {
emitSessionStart('session-2', 'session-1');

expect(emit).toHaveBeenCalledWith({
body: 'Session started.',
attributes: {
'event.name': 'session.start',
'session.id': 'session-2',
'session.previous_id': 'session-1',
},
});
});

it('does not claim continuation for a replacement session', () => {
emitSessionStart('session-2');

expect(emit).toHaveBeenCalledWith({
body: 'Session started.',
attributes: {
'event.name': 'session.start',
'session.id': 'session-2',
},
});
});

it('emits the required attributes for session.end', () => {
emitSessionEnd('session-1');

expect(emit).toHaveBeenCalledWith({
body: 'Session ended.',
attributes: {
'event.name': 'session.end',
'session.id': 'session-1',
},
});
});
});
39 changes: 39 additions & 0 deletions packages/core/src/telemetry/session-events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import { logs } from '@opentelemetry/api-logs';
import type { LogAttributes } from '@opentelemetry/api-logs';
import {
EVENT_SESSION_END,
EVENT_SESSION_START,
SERVICE_NAME,
} from './constants.js';

export function emitSessionStart(
sessionId: string,
previousSessionId?: string,
): void {
const attributes: LogAttributes = {
'event.name': EVENT_SESSION_START,
'session.id': sessionId,
...(previousSessionId ? { 'session.previous_id': previousSessionId } : {}),
};

logs.getLogger(SERVICE_NAME).emit({
body: 'Session started.',
attributes,
});
}

export function emitSessionEnd(sessionId: string): void {
logs.getLogger(SERVICE_NAME).emit({
body: 'Session ended.',
attributes: {
'event.name': EVENT_SESSION_END,
'session.id': sessionId,
},
});
}
Loading