Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,14 @@ to Socket as a small JSON event. An event holds the event name (for example
`patch_applied` or `patch_scan_failed`), the subcommand, the CLI version, the
operating system and CPU architecture, a timestamp, a random ID generated for
that one run, and a few counters and flags for the command (such as patches
applied, packages scanned, ecosystems found, the patch mode, `dry_run`). `get`
adds the patch UUID. A failure adds the error message, with URL credentials
redacted and your home directory replaced by `~`. Apart from what an error
message quotes, events hold no package names, file paths, file contents, or
dependency lists.
applied, packages scanned, ecosystems found, the patch mode, `dry_run`). An
event about specific patches (downloading, applying, vendoring, removing, or
rolling them back) names each by its patch UUID, with its ecosystem, mode, and
outcome; a patch UUID tells Socket which package version the patch is for. A
failure adds an error code and the error message, with URL credentials redacted
and your home directory replaced by `~`. Apart from those patch UUIDs and what
an error message quotes, events hold no package names, file paths, file
contents, or dependency lists.

Events go to `api.socket.dev` with your API token when a token and organization
are configured, otherwise anonymously to `patches-api.socket.dev`. They are sent
Expand Down
26 changes: 16 additions & 10 deletions crates/socket-patch-cli/CLI_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -2021,9 +2021,13 @@ State lives at `$XDG_CACHE_HOME`|`~/.cache` (Unix/macOS) or `%LOCALAPPDATA%` (Wi

## Telemetry

Telemetry is **on by default**. Each command reports its outcome as one JSON event per row of the table below (a `scan` or `get` that also applies sends two).
Telemetry is **on by default**. Each command reports its outcome as one JSON event per row of the table below (a `scan` or `get` that also downloads and applies sends up to three; a `scan` over several project directories reports each).

**What is sent.** `{event_sender_created_at, event_type, context: {version, platform, arch, command}, session_id, metadata?, error?: {type, message}}`; no `event_kind`, so the backend stores it as a required event. `context` is the client version, `std::env::consts::OS` / `ARCH` and the subcommand. `session_id` is a random UUID generated per process and never stored, so it links the events of one run and nothing else. `metadata` holds only the per-event fields in the table. `error.message` (failure events) has every URL redacted (userinfo, grant tokens, signed query values) and the home directory replaced by `~`; it can otherwise quote a package name or a path. The request carries `User-Agent: SocketPatchCLI/<version>` and, on the org route, `Authorization: Bearer <token>`. Nothing else is sent: no package list, no file contents, no machine identifier.
**What is sent.** `{event_sender_created_at, event_type, context: {version, platform, arch, command, channel?}, session_id, metadata?, error?: {type, message}}`; no `event_kind`, so the backend stores it as a required event. `context` is the client version, `std::env::consts::OS` / `ARCH`, the subcommand, and `channel`: the install channel of the running binary (`npm`, `cargo`, `homebrew`, `pypi`, `launcher_cache`, or `standalone` for any location none of those owns; the same detection `--update` uses, from the binary's canonical path, read from environment variables alone and resolved before `--update` swaps the binary), omitted when that path cannot be read. `session_id` is a random UUID generated per process and never stored, so it links the events of one run and nothing else. `metadata` holds only the per-event fields in the table. `error.message` (failure events) has every URL redacted (userinfo, grant tokens, signed query values), the home directory replaced by `~`, and is cut to 1,000 characters; it can otherwise quote a package name or a path. The request carries `User-Agent: SocketPatchCLI/<version>` and, on the org route, `Authorization: Bearer <token>`. Nothing else is sent: no package name, no file contents, no machine identifier. The patches an event names are named by patch UUID (see below), which identifies a patched package version to Socket.

**Patches.** An event about specific patches (the rows marked *patches*) adds to `metadata`: `patches`, at most 50 `{uuid, ecosystem, mode, outcome, code?}` entries, one per patch and mode, failed ones first (`mode`: `agent` / `hosted` / `vendored`; `outcome`: `applied`, `downloaded`, `rolled_back`, `removed`, `rebuilt`, `verified` (a dry run), `skipped`, `failed`; `code` is the event's `errorCode`, on `skipped` and `failed` only); `patches_truncated: true` when the cap dropped entries; `outcomes`, the count of patches per outcome over the whole run; and `ecosystems` / `modes`, their distinct values. They are derived from the run's `--json` events, so the two cannot disagree: several events for one patch (one per installed copy) fold into the one that says most (a failure over a change, a change over a preview, a preview over a skip). A run that named no patch adds none of these. The event body stays under 9,000 bytes (the server's dashboards cannot read one past 10,000 characters): an event that would not fit gives up the tail of its error message, down to 200 characters, and then entries off the end of its patch list.

**Failures.** Every failure event carries `error_code`: the code the run's `--json` envelope reports as its `error.code` (`patch_not_found`, `rollback_failed`, `vendor_revert_kept`, …), so a mistyped target is distinguishable from a patch that failed. It is the same with and without `--json`. A run whose envelope has failed events and no top-level error reports `apply_failed`, `vendor_failed`, `hosted_failed` or `repair_failed`. Two kinds of run report nothing, in every command: one that exits 2 on a usage error, and one that could not take the apply lock.

**Where.** `POST <api>/v0/orgs/<org>/telemetry` with the bearer when the run has a token and an org, else anonymously `POST <proxy>/patch/telemetry` (`--api-url` / `--proxy-url` and their env vars move both). The route is the run's API client's when the run built one, so telemetry follows the same host and org as its API calls. A run that built no client (see [API client construction](#api-client-construction)) takes the route from the configured credentials alone (flag → env → socket-cli config, no network): a token with no configured org then reports anonymously, because the org is never looked up only to address an event.

Expand All @@ -2044,14 +2048,16 @@ Every `event_type` must be in the Socket API's patch event map, or it is stored

| Command | Success | Failure | Metadata |
|---|---|---|---|
| `scan` | `patch_scanned` | `patch_scan_failed` | `packages_scanned`, `free_patches`, `paid_patches`, `can_access_paid`, `ecosystems` (found by the crawl), `fallback_to_proxy`, `mode` (requested: `hosted` / `vendored` / `agent`, or `report` with none), `project_modes` (already wired: `hosted` lockfile pins, `vendored` ledger, `agent` manifest) |
| `scan`/`get --mode hosted` (non-empty selection) | `patch_applied` | `patch_apply_failed` | `mode: "hosted"`, `patches_count` (pins confirmed), `files_count` (files rewritten), `dry_run` |
| `apply` (and the nested apply of `scan`/`get --mode agent`) | `patch_applied` | `patch_apply_failed` | `mode: "agent"`, `patches_count`, `dry_run` |
| `vendor` / `scan`/`get --mode vendored` | `patch_vendored` | `patch_vendor_failed` | `patches_count`, `dry_run` |
| `get` | `patch_fetched` | `patch_fetch_failed` | `uuid`, `tier`, `ecosystem`, `download_mode`, `fallback_to_proxy` |
| `remove` / `rollback` | `patch_removed` / `patch_rolled_back` | `patch_remove_failed` / `patch_rollback_failed` | `removed_count` / `rolled_back_count` |
| `list` / `repair` | `patch_listed` / `patch_repaired` | — / `patch_repair_failed` | `patches_count` / `blobs_added`, `blobs_removed`, `bytes_freed` |
| `vex` | `vex_generated` | `vex_failed` | `advisories_count`, `format`, `output_kind` |
| `scan` (one per project directory) | `patch_scanned` | `patch_scan_failed` | `packages_scanned`, `free_patches`, `paid_patches`, `can_access_paid`, `ecosystems` (found by the crawl), `packages_by_ecosystem` / `patches_by_ecosystem` (ecosystem → count), `fallback_to_proxy`, `mode` (requested: `hosted` / `vendored` / `agent`, or `report` with none), `project_modes` (already wired: `hosted` lockfile pins, `vendored` ledger, `agent` manifest), `dry_run`. Failure: `error_code`, `fallback_to_proxy`, `mode` |
| `scan`/`get --mode hosted` (non-empty selection) | `patch_applied` | `patch_apply_failed` | `mode: "hosted"`, `patches_count` (pins confirmed), `files_count` (files rewritten), `dry_run`, *patches* |
| `apply` (and the nested apply of `scan`/`get --mode agent`, reported under `scan` / `get`) | `patch_applied` | `patch_apply_failed` | `mode: "agent"`, `patches_count` (packages patched; on a failure, what the run did apply), `dry_run`, *patches* |
| `scan --mode agent`, `get <purl\|advisory>` in agent mode (a run that reached a patch) | `patch_fetched` | — | `mode: "agent"`, `patches_count` (records downloaded), `download_mode`, *patches* (`downloaded`, `skipped` / `already_in_manifest`, `failed`) |
| `vendor` / `scan`/`get --mode vendored` (reported under the command run) | `patch_vendored` | `patch_vendor_failed` | `mode: "vendored"`, `patches_count`, `dry_run`, *patches* |
| `get <uuid>` | `patch_fetched` | `patch_fetch_failed` | `uuid`, `tier`, `ecosystem`, `mode`, `patches_count: 1`, `download_mode`, `fallback_to_proxy`, *patches*. Failure: `uuid` (when one was asked for), `error_code` (`not_found`, `paid_required`, `patch_fetch_failed`), `fallback_to_proxy` |
| `remove`, `vendor --revert` (never on `--dry-run`; one event per run) | `patch_removed` | `patch_remove_failed` | `removed_count` (patches taken out), *patches* |
| `rollback` | `patch_rolled_back` | `patch_rollback_failed` | `rolled_back_count` (packages restored, as `summary.rolledBack`), `dry_run`, `targeted` (targets were named), *patches* |
| `list` / `repair` | `patch_listed` / `patch_repaired` | — / `patch_repair_failed` | `patches_count` / `blobs_added`, `blobs_removed`, `bytes_freed`. Failure: `error_code` |
| `vex` | `vex_generated` | `vex_failed` | `advisories_count`, `format`, `output_kind`. Failure: `error_code` |
| `--update` (an install, not a no-op or `--dry-run`) | `cli_updated` | `cli_update_failed` | `from_version`, `to_version`, `channel`, `pinned`, `forced` / `error_code` (the envelope's) |

## Environment variables
Expand Down
50 changes: 50 additions & 0 deletions crates/socket-patch-cli/src/commands/agent_download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1593,6 +1593,18 @@ pub(crate) struct DetachedDownload {
}

impl DetachedDownload {
/// The patches the phase could not download, as the run's telemetry
/// names them: the vendor step never sees these (it works from the
/// records that did download), so its event adds them.
pub(crate) fn failed_outcomes(&self) -> Vec<socket_patch_core::telemetry::PatchOutcome> {
crate::telemetry_outcomes::patch_outcomes_of(
self.events
.iter()
.filter(|event| event.action == EventAction::Failed),
socket_patch_core::telemetry::MODE_VENDORED,
)
}

/// Fold the phase's events and warnings into `env` (records via
/// [`Envelope::record`], so `summary` and `status` follow) and hand back
/// the exit code and the records.
Expand Down Expand Up @@ -1826,6 +1838,33 @@ pub(crate) fn nested_apply_args_from_params(
nested_apply_args(&common, manifest_path, params.quiet())
}

/// The patches an agent-mode download pass reached, as its telemetry
/// names them: a patch fetched in place of an older one is `downloaded`
/// like any other.
fn fetched_outcomes(events: &[PatchEvent]) -> Vec<socket_patch_core::telemetry::PatchOutcome> {
let events: Vec<PatchEvent> = events
.iter()
.map(|event| PatchEvent {
action: match event.action {
EventAction::Updated => EventAction::Downloaded,
action => action,
},
..event.clone()
})
.collect();
crate::telemetry_outcomes::patch_outcomes_of(&events, socket_patch_core::telemetry::MODE_AGENT)
}

/// The command an engine run's telemetry reports: the one whose envelope
/// it fills. `scan` and `get` are the engine's two callers; both pass
/// their own envelope, printed or not.
pub(crate) fn telemetry_command(env: &Envelope) -> &'static str {
match env.command {
EnvelopeCommand::Scan => "scan",
_ => "get",
}
}

/// Run the nested `apply` step with `common` (see [`nested_apply_args`])
/// on the caller's `client`, under the apply `lock` the caller took for
/// its manifest write — one lock window for download → manifest write →
Expand All @@ -1839,6 +1878,7 @@ pub(crate) fn nested_apply_args_from_params(
/// opt-in on the top-level command only, never on this internal
/// invocation.
pub(crate) async fn run_nested_apply(
command: &'static str,
common: GlobalArgs,
json: bool,
report_user_patch_skips: bool,
Expand All @@ -1856,6 +1896,7 @@ pub(crate) async fn run_nested_apply(
nested: Some(super::apply::NestedApply {
caller_json: json,
report_user_patch_skips,
command,
}),
};
// The nested apply runs on the host's client: seeded, never rebuilt.
Expand Down Expand Up @@ -2228,6 +2269,14 @@ pub async fn download_and_apply_patches_into(
// single-uuid flow's summary in `save_and_apply_patch`; their sum gates
// the apply step.
let downloaded = batch.fetched.len();
// Telemetry: the patch records this run fetched. `get <uuid>` reports
// its own fetch; every other agent-mode download comes through here.
socket_patch_core::telemetry::track_patches_fetched(
telemetry_command(env),
&fetched_outcomes(&batch.events),
&socket_patch_core::telemetry::TelemetryAuth::for_client(run.api_client),
)
.await;
let mut updated = 0usize;
let mut new_blobs: Vec<String> = Vec::new();
// `(purl, uuid)` of every selected patch now recorded: the fetched ones
Expand Down Expand Up @@ -2331,6 +2380,7 @@ pub async fn download_and_apply_patches_into(
crate::hot_patch::mark_apply_started();
apply_report = Some(
run_nested_apply(
telemetry_command(env),
nested_apply_args_from_params(params, run, &manifest_path),
params.json,
!params.user_patch_skips_reported,
Expand Down
60 changes: 58 additions & 2 deletions crates/socket-patch-cli/src/commands/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ pub struct NestedApply {
/// (`get`) checked only its own selection. `scan` already reported
/// every protected installed package, so it passes `false`.
pub report_user_patch_skips: bool,
/// The command the user ran (`scan`, `get`): what the nested run's
/// telemetry reports as its command.
pub command: &'static str,
}

impl ApplyArgs {
Expand Down Expand Up @@ -1610,6 +1613,12 @@ pub(crate) async fn run_locked(

// Packages the project patched itself sit this run out (warned); every
// other record still applies. The read-only `--check` verifies them all.
// Each record's patch, for telemetry: results name the package only.
let patch_uuids: HashMap<String, String> = manifest
.patches
.iter()
.map(|(purl, record)| (purl.clone(), record.uuid.clone()))
.collect();
let mut manifest = manifest;
let (user_patch_warnings, user_patch_skips) = if args.check {
Default::default()
Expand Down Expand Up @@ -2133,12 +2142,23 @@ pub(crate) async fn run_locked(
}

// Track telemetry
let reported = reported_patches(&results, &caveats, args.common.dry_run, &patch_uuids);
if success {
track_patch_applied(patched_count, args.common.dry_run, &telemetry()).await;
track_patch_applied(
telemetry_command(&args),
patched_count,
args.common.dry_run,
&reported,
&telemetry(),
)
.await;
} else {
track_patch_apply_failed(
telemetry_command(&args),
"apply_failed",
"One or more patches failed to apply",
args.common.dry_run,
&reported,
&telemetry(),
)
.await;
Expand Down Expand Up @@ -2218,6 +2238,34 @@ pub(crate) async fn run_locked(
}
}

/// The command an apply run's telemetry reports: `apply`, or the `scan` /
/// `get` whose agent mode ran it.
fn telemetry_command(args: &ApplyArgs) -> &'static str {
args.nested.map_or("apply", |nested| nested.command)
}

/// The patches an apply run acted on, as its telemetry names them: the
/// run's per-package events ([`GemCaveats::event_of`], what `--json`
/// prints), each under the patch its manifest record names.
///
/// A plain fn, so the events it builds stay off the async frame of `run`.
fn reported_patches(
results: &[ApplyResult],
caveats: &GemCaveats,
dry_run: bool,
patch_uuids: &HashMap<String, String>,
) -> Vec<socket_patch_core::telemetry::PatchOutcome> {
let events: Vec<PatchEvent> = results
.iter()
.map(|result| caveats.event_of(result, dry_run))
.collect();
crate::telemetry_outcomes::patch_outcomes(
&events,
socket_patch_core::telemetry::MODE_AGENT,
crate::telemetry_outcomes::uuid_lookup(patch_uuids),
)
}

/// The one apply-failure exit: `apply_failed` telemetry, then the error
/// envelope (`--json`) or an `Error:` line that prints even under
/// `--silent` ("errors only", never "nothing" — exit 1 with no message
Expand All @@ -2232,7 +2280,15 @@ async fn report_apply_failure(
skipped: &[PatchEvent],
telemetry: &TelemetryAuth,
) -> i32 {
track_patch_apply_failed(error, args.common.dry_run, telemetry).await;
track_patch_apply_failed(
telemetry_command(args),
&err.code,
error,
args.common.dry_run,
&[],
telemetry,
)
.await;
if args.common.json {
let mut env = Envelope::new(Command::Apply);
env.dry_run = args.common.dry_run;
Expand Down
Loading
Loading