-
Notifications
You must be signed in to change notification settings - Fork 20
feat(cli): add telemetry client library #930
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
packages/nemo_platform_ext/src/nemo_platform_ext/cli/telemetry/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| from nemo_platform_ext.cli.telemetry.handler import ( | ||
| QueuedEvent, | ||
| TelemetryHandler, | ||
| build_payload, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "QueuedEvent", | ||
| "TelemetryHandler", | ||
| "build_payload", | ||
| ] |
99 changes: 99 additions & 0 deletions
99
packages/nemo_platform_ext/src/nemo_platform_ext/cli/telemetry/emit.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| """Fire-and-flush emission with three opt-out layers and the first-run notice.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| from nemo_platform_ext.cli.telemetry.events import PlatformTelemetryEvent | ||
| from nemo_platform_ext.cli.telemetry.handler import TelemetryHandler, _telemetry_enabled | ||
| from nemo_platform_ext.cli.telemetry.session import get_session_id | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _invocation_opt_out = False | ||
|
|
||
| _NOTICE_TEXT = ( | ||
| "NeMo Platform CLI telemetry is on by default and sends anonymous usage data to improve the product. " | ||
| "It does not send prompts, model inputs or outputs, datasets, secrets, file contents, or personal identifiers. " | ||
| "Turn it off with NEMO_TELEMETRY_ENABLED=false or telemetry_enabled: false in the CLI config. " | ||
| "Run nemo docs cli/configuration for details.\n" | ||
|
mckornfield marked this conversation as resolved.
|
||
| ) | ||
|
|
||
|
|
||
| def set_invocation_opt_out(value: bool) -> None: | ||
| """Per-invocation opt-out (e.g. a --no-telemetry flag on the current command).""" | ||
| global _invocation_opt_out | ||
| _invocation_opt_out = value | ||
|
|
||
|
|
||
| def _config_opted_out() -> bool: | ||
| """True when the persisted config file sets ``telemetry_enabled: false``.""" | ||
| try: | ||
| from nemo_platform_ext.config.config import Config | ||
|
|
||
| cfg = Config.load() | ||
| return cfg.get_config_file().telemetry_enabled is False | ||
| except Exception: | ||
| # A privacy control must fail closed: if we cannot read the config to confirm | ||
| # the user is opted in, treat them as opted out and do not send. | ||
| logger.debug("Could not read telemetry opt-out config; failing closed (opted out)", exc_info=True) | ||
| return True | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
|
|
||
| def telemetry_opted_in() -> bool: | ||
| """Opted in only when all three layers agree: per-invocation, env, and config.""" | ||
| if _invocation_opt_out: | ||
| return False | ||
| if not _telemetry_enabled(): | ||
| return False | ||
| return not _config_opted_out() | ||
|
|
||
|
|
||
| def _client_version() -> str: | ||
| try: | ||
| import nemo_platform | ||
|
|
||
| return nemo_platform.__version__ | ||
| except Exception: | ||
| logger.debug("Could not resolve client version for telemetry", exc_info=True) | ||
| return "undefined" | ||
|
|
||
|
|
||
| def emit_event(event: PlatformTelemetryEvent) -> None: | ||
| """Best effort. Telemetry must never break a user command.""" | ||
| try: | ||
| if not telemetry_opted_in(): | ||
| return | ||
| # No retries on the CLI exit path: a synchronous send blocks the user's command, | ||
| # so cap the worst case at one bounded send (SEND_TIMEOUT_SECONDS) rather than | ||
| # retrying against a slow or unreachable endpoint while the user waits. | ||
| handler = TelemetryHandler(source_client_version=_client_version(), session_id=get_session_id(), max_retries=0) | ||
| handler.enqueue(event) | ||
| handler.stop() | ||
| except Exception: | ||
| logger.debug("Failed to emit telemetry event", exc_info=True) | ||
|
|
||
|
|
||
| def _notice_marker_path() -> Path: | ||
| from nemo_platform_ext.config.config import Config | ||
|
|
||
| return Config.get_default_config_path().parent / "telemetry-notice-shown" | ||
|
|
||
|
|
||
| def maybe_print_first_run_notice() -> None: | ||
| """Print the first-run notice to stderr once. Stdout stays machine-clean.""" | ||
| try: | ||
| if not telemetry_opted_in(): | ||
| return | ||
| marker = _notice_marker_path() | ||
| if marker.exists(): | ||
| return | ||
| marker.parent.mkdir(parents=True, exist_ok=True) | ||
| marker.touch() | ||
| sys.stderr.write(_NOTICE_TEXT) | ||
|
mckornfield marked this conversation as resolved.
|
||
| except Exception: | ||
| logger.debug("Failed to print telemetry notice", exc_info=True) | ||
97 changes: 97 additions & 0 deletions
97
packages/nemo_platform_ext/src/nemo_platform_ext/cli/telemetry/events.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| """Platform usage-telemetry event models. | ||
|
|
||
| Field names and aliases follow the shared NeMo telemetry schema | ||
| (aire/microservices/nemo-telemetry, schemas/anonymous_events.json, v1.9). | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from enum import Enum | ||
| from typing import ClassVar | ||
|
|
||
| from pydantic import BaseModel, ConfigDict, Field | ||
|
|
||
| _CI_ENV_VARS = ( | ||
| "CI", | ||
| "GITLAB_CI", | ||
| "GITHUB_ACTIONS", | ||
| "BUILDKITE", | ||
| "CIRCLECI", | ||
| "JENKINS_URL", | ||
| "TEAMCITY_VERSION", | ||
| "TF_BUILD", | ||
| "TRAVIS", | ||
| ) | ||
| _FALSEY = ("", "0", "false", "no", "off") | ||
|
|
||
|
|
||
| def is_ci_environment() -> bool: | ||
| return any(os.getenv(v, "").lower() not in _FALSEY for v in _CI_ENV_VARS) | ||
|
|
||
|
|
||
| class TaskStatusEnum(str, Enum): | ||
| COMPLETED = "completed" | ||
| ERROR = "error" | ||
| CANCELED = "canceled" | ||
| UNDEFINED = "undefined" | ||
|
|
||
|
|
||
| class DeploymentTypeEnum(str, Enum): | ||
| CLI = "cli" | ||
| SDK = "sdk" | ||
| NVIDIA_INTERNAL = "nvidia-internal" | ||
| UNDEFINED = "undefined" | ||
|
|
||
|
|
||
| def _deployment_type() -> DeploymentTypeEnum: | ||
| raw = os.getenv("NEMO_DEPLOYMENT_TYPE", "cli").lower() | ||
| try: | ||
| return DeploymentTypeEnum(raw) | ||
| except ValueError: | ||
| return DeploymentTypeEnum.UNDEFINED | ||
|
|
||
|
|
||
| class PlatformTelemetryEvent(BaseModel): | ||
| """Base for all platform events. extra="forbid" is a privacy guard.""" | ||
|
mckornfield marked this conversation as resolved.
|
||
|
|
||
| model_config = ConfigDict(extra="forbid", populate_by_name=True) | ||
|
|
||
| _event_name: ClassVar[str] = "undefined" | ||
| _schema_version: ClassVar[str] = "1.9" | ||
|
|
||
| nemo_source: str = Field(default="platform", serialization_alias="nemoSource") | ||
| task_status: TaskStatusEnum = Field(serialization_alias="taskStatus") | ||
| deployment_type: DeploymentTypeEnum = Field(default_factory=_deployment_type, serialization_alias="deploymentType") | ||
| is_ci: bool = Field(default_factory=is_ci_environment, serialization_alias="isCi") | ||
|
|
||
|
|
||
| class OnboardingStepEvent(PlatformTelemetryEvent): | ||
| _event_name: ClassVar[str] = "onboarding_step" | ||
|
|
||
| step: str | ||
| provider_type: str = Field(default="undefined", serialization_alias="providerType") | ||
| models_discovered_bucket: str = Field(default="undefined", serialization_alias="modelsDiscoveredBucket") | ||
| skills_target: str = Field(default="undefined", serialization_alias="skillsTarget") | ||
| agent_deployed: bool = Field(default=False, serialization_alias="agentDeployed") | ||
|
|
||
|
|
||
| class CommandInvokedEvent(PlatformTelemetryEvent): | ||
| _event_name: ClassVar[str] = "command_invoked" | ||
|
|
||
| command: str | ||
| duration_sec: float = Field(serialization_alias="durationSec") | ||
| agent_mode: bool = Field(default=False, serialization_alias="agentMode") | ||
|
|
||
|
|
||
| class JobRunEvent(PlatformTelemetryEvent): | ||
| _event_name: ClassVar[str] = "job_run" | ||
|
|
||
| job_type: str = Field(serialization_alias="jobType") | ||
| duration_sec: float = Field(default=-1.0, serialization_alias="durationSec") | ||
| plugins: list[str] = Field(default_factory=list) | ||
| model: str = "undefined" | ||
| input_tokens: int = Field(default=-1, serialization_alias="inputTokens") | ||
| output_tokens: int = Field(default=-1, serialization_alias="outputTokens") | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.