Compare commits

..
Author SHA1 Message Date
CodeWhale Bot ac501c9562 wip: coarse install-age bucket (C2) 2026-11-12 20:02:53 -08:00
CodeWhale Bot d7cadafbab wip: client schema 6 contract (S6-C) 2026-11-12 20:00:57 -08:00
CodeWhale BotandClaude Sonnet 5.5 f03f69e086 chore(telemetry): collector accepts runtime schema 6 and keeps schemas 1 to 5
Schema 6 (notice 8) carries the exact key sets the client slice will send:
model_usage counters gain requests, reasoning_tokens and generation_secs, and
model_usage gains a context object of four input-size request counts; the
session_start event gains install_age; exec sources gain fleet_worker, agent
and scripted; exit_class gains unclean. Each is accepted on v6 only, so a v1
to v5 batch is validated exactly as before and a v4 batch carrying any v6 key
or value is still refused. The preUsage shortcut becomes one explicit boolean
per version.

Rows append: model_usage double12..18 (0 on v4 rows, blob19 tells them
apart) and install_age in blob12 of session_start rows. generation_secs is a
whole-second session sum rather than milliseconds, so a one-request session
does not reveal an exact request duration. PostHog forwarding is untouched,
so v6 stays first-party only. report-funnel reads v4 and v6 model usage and
excludes fleet_worker, agent and scripted starts as it does ci. A
hand-authored crates/telemetry/tests/golden/v6.json is the contract fixture.

The doc-welded constants (SCHEMA_VERSION, EVENT_FIELDS, SESSION_SOURCES,
EXIT_CLASSES) stay at their v4 values until the client slice updates
docs/TELEMETRY.md; the v6 sets are separate constants.

Checks: telemetry-ingest npm test 225 passed 0 failed (8 files), tsc
--noEmit clean, wrangler dev --local answered 204 to v4.json and v6.json and
400 to a v6 batch with a free-text install_age, wrangler deploy --dry-run ok,
cargo fmt --all -- --check ok, scripts/preflight.sh --check OK.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 19:56:12 -08:00
CodeWhale Bot 84a359272f wip: telemetry names the resolved wire model through aliases (CW-8190) 2026-11-12 19:55:49 -08:00
48 changed files with 1248 additions and 120 deletions

No files matched your search

Generated
+34
View File
@@ -907,6 +907,7 @@ dependencies = [
"serde",
"serde_json",
"tempfile",
"toml 1.1.6+spec-1.1.0",
"webbrowser",
"zeroize",
]
@@ -1149,6 +1150,7 @@ dependencies = [
"sha2 0.11.1",
"tempfile",
"thiserror 2.0.21",
"tokio",
"uuid",
]
@@ -1219,6 +1221,7 @@ dependencies = [
"codewhale-util",
"codewhale-workflow",
"codewhale-workflow-js",
"cucumber",
"dirs 7.0.0",
"encoding_rs",
"fd-lock",
@@ -1237,10 +1240,12 @@ dependencies = [
"objc2-foundation",
"parking_lot",
"portable-pty",
"pretty_assertions",
"proc-macro2",
"regex",
"reqwest",
"ring",
"rio-vt",
"rmcp",
"rusqlite",
"rustls",
@@ -1256,7 +1261,9 @@ dependencies = [
"tar",
"tempfile",
"thiserror 2.0.21",
"tiny_http",
"tokio",
"tokio-tungstenite 0.30.0",
"tokio-util",
"toml 1.1.6+spec-1.1.0",
"toml_edit 0.25.15+spec-1.1.0",
@@ -1609,6 +1616,7 @@ dependencies = [
"colored",
"dirs 7.0.0",
"fd-lock",
"futures-util",
"ignore",
"jsonwebtoken",
"libc",
@@ -1870,12 +1878,15 @@ dependencies = [
"objc2-foundation",
"parking_lot",
"portable-pty",
"pretty_assertions",
"ratatui",
"regex",
"reqwest",
"rio-vt",
"rquickjs",
"rusqlite",
"rustls",
"schemars 1.2.2",
"semver",
"serde",
"serde_json",
@@ -1885,6 +1896,7 @@ dependencies = [
"tempfile",
"tiny_http",
"tokio",
"tokio-tungstenite 0.30.0",
"tokio-util",
"toml 1.1.6+spec-1.1.0",
"toml_edit 0.25.15+spec-1.1.0",
@@ -2460,6 +2472,12 @@ dependencies = [
"unicode-xid",
]
[[package]]
name = "diff"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
[[package]]
name = "digest"
version = "0.10.7"
@@ -5661,6 +5679,16 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "pretty_assertions"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d"
dependencies = [
"diff",
"yansi",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
@@ -8815,6 +8843,12 @@ dependencies = [
"hashlink",
]
[[package]]
name = "yansi"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"
[[package]]
name = "yoke"
version = "0.8.3"
+1
View File
@@ -23,5 +23,6 @@ reqwest = { workspace = true, features = ["blocking"] }
serde.workspace = true
serde_json.workspace = true
tempfile.workspace = true
toml.workspace = true
webbrowser = "1.0"
zeroize = "1.8.2"
+22
View File
@@ -180,6 +180,28 @@ impl ModelRegistry {
self.models.clone()
}
/// Returns whether a selector is known only outside the selected provider.
///
/// This is rejection metadata, never route authority: callers may use it
/// to reject a clearly foreign model, but must not use the matching row to
/// select a provider or credential slot.
#[must_use]
pub fn is_known_for_other_provider(
&self,
requested: &str,
selected_provider: ProviderKind,
) -> bool {
let known_here = self
.models
.iter()
.any(|model| model.provider == selected_provider && model_matches(model, requested));
!known_here
&& self
.models
.iter()
.any(|model| model.provider != selected_provider && model_matches(model, requested))
}
/// Resolves a user-requested model name to a concrete [`ModelInfo`].
///
/// Resolution follows this priority order:
+1
View File
@@ -3049,6 +3049,7 @@ fn start_cli_telemetry(
telemetry::init(consent);
telemetry::record(Event::SessionStart {
source: SessionSource::Unknown,
install_age: telemetry::install_age(),
});
Some(CliTelemetrySession {
started: std::time::Instant::now(),
+16
View File
@@ -484,6 +484,22 @@ pub fn public_model_identifier(model: &str) -> bool {
})
}
/// Case-insensitive form of [`public_model_identifier`] for ids that were
/// lowercased before the lookup.
#[must_use]
pub fn public_model_identifier_ignore_case(model: &str) -> bool {
let catalog = super::bundled_models_dev_catalog();
let matches = |id: &str| id.eq_ignore_ascii_case(model);
catalog.reviewed.intrinsic.keys().any(|id| matches(id))
|| catalog.models.keys().any(|id| matches(id))
|| catalog.providers.values().any(|provider| {
provider
.models
.iter()
.any(|(id, row)| matches(id) || matches(&row.id))
})
}
#[must_use]
pub fn official_deepseek_model_id(model: &str) -> Option<&'static str> {
bundled_reviewed()
+13
View File
@@ -434,6 +434,19 @@ impl ConfigToml {
}
}
/// The unquoted contents of an extras key that holds a TOML string.
///
/// [`ConfigToml::get_value`] renders extras through `toml::Value::to_string`,
/// which re-applies TOML quoting — and switches to a single-quoted literal
/// string whenever the payload contains a `"`. A JSON blob written with
/// [`ConfigToml::set_value`] therefore comes back as `'[{"a":1}]'` and no
/// longer parses as JSON (#4727). Callers that stored structured text want
/// the payload, not its TOML rendering.
#[must_use]
pub fn get_raw_string(&self, key: &str) -> Option<&str> {
self.extras.get(key).and_then(toml::Value::as_str)
}
#[must_use]
pub fn get_display_value(&self, key: &str) -> Option<String> {
if let Some(alias) = self.root_alias_key(key) {
+4
View File
@@ -22,6 +22,10 @@ use crate::route::{
WireModelId,
};
/// Provider catalog endpoint used by Models.dev.
pub const MODELS_DEV_API_URL: &str = "https://models.dev/api.json";
/// Provider-agnostic model metadata endpoint used by Models.dev.
pub const MODELS_DEV_MODELS_URL: &str = "https://models.dev/models.json";
/// Combined `{ models, providers }` endpoint used by Models.dev.
pub const MODELS_DEV_CATALOG_URL: &str = "https://models.dev/catalog.json";
+14
View File
@@ -522,6 +522,20 @@ impl OfferingPricing {
None
}
/// Per-million price for one canonical class, when published.
#[must_use]
pub fn price_per_million(&self, class: TokenClass) -> Option<f64> {
match class {
TokenClass::Input => self.input_per_million,
TokenClass::Output => self.output_per_million,
TokenClass::CacheRead => self.cache_read_per_million,
TokenClass::CacheWrite => self.cache_write_per_million,
TokenClass::Reasoning => self.reasoning_per_million,
TokenClass::InputAudio => self.input_audio_per_million,
TokenClass::OutputAudio => self.output_audio_per_million,
}
}
/// Classes this turn actually used that carry no published price.
///
/// Non-empty means [`Self::estimate_cost`] fails closed for this usage; the
+1 -1
View File
@@ -45,7 +45,7 @@ pub const SETUP_STATE_FILE_NAME: &str = "setup_state.json";
/// when the collection policy, schema, or disclosure materially changes. Prior
/// declines remain off. Keying it to the app version would re-prompt every
/// release, which is nagging with extra steps.
pub const TELEMETRY_NOTICE_VERSION: &str = "6";
pub const TELEMETRY_NOTICE_VERSION: &str = "8";
/// Canonical setup step ids. The ordering matches the first-run spine so a
/// `BTreeMap<SetupStep, _>` renders in wizard order.
+1
View File
@@ -24,3 +24,4 @@ serde_json = { workspace = true, features = ["preserve_order"] }
[dev-dependencies]
tempfile.workspace = true
uuid.workspace = true
tokio = { workspace = true, features = ["macros", "rt", "time"] }
+4
View File
@@ -60,6 +60,10 @@ impl Thread {
pub fn leaf_id(&self) -> Option<&str> {
self.leaf_id.as_deref()
}
pub fn set_leaf(&mut self, leaf: Option<String>) {
self.leaf_id = leaf;
}
}
/// Ephemeral session within a thread (one engine lifetime / one turn's
+5
View File
@@ -203,9 +203,14 @@ codewhale-util = { path = "../util", version = "0.10.3", features = ["test-suppo
codewhale-models = { path = "../models", version = "0.10.3", features = [
"test-support",
] }
cucumber = "0.23.0"
wiremock = "0.6"
tiny_http = "0.12"
pretty_assertions = "1.4"
rio-vt = "0.5.1"
rusqlite.workspace = true
schemars = { version = "1.2.1", features = ["derive", "preserve_order"] }
tokio-tungstenite = "0.30"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
+1
View File
@@ -11793,6 +11793,7 @@ fn record_model_turn_telemetry(
{
return;
}
let model = turn.last_parent_model.as_deref().unwrap_or(model);
let outcome = match status {
TurnOutcomeStatus::Completed => codewhale_telemetry::TurnOutcome::Ok,
TurnOutcomeStatus::Failed => codewhale_telemetry::TurnOutcome::Failed,
+1
View File
@@ -73,6 +73,7 @@ include!("tests/test_cases_18.rs");
include!("tests/test_cases_19.rs");
mod admission_gates;
mod model_turn_telemetry;
mod redacted_thinking;
mod runtime_state;
mod sse_turn_recovery;
@@ -0,0 +1,31 @@
use super::*;
#[test]
fn model_turn_telemetry_names_the_model_the_last_request_used() {
let mut turn = crate::core::turn::TurnContext::new(4);
turn.add_parent_usage(&Usage {
input_tokens: 10,
output_tokens: 5,
..Usage::default()
});
turn.note_parent_model("deepseek-v4pro");
record_model_turn_telemetry(
codewhale_config::ProviderKind::Deepseek,
"auto",
&turn,
TurnOutcomeStatus::Completed,
);
let reported = codewhale_telemetry::session_counters()
.usage_events()
.into_iter()
.any(|event| {
matches!(
event,
codewhale_telemetry::Event::ModelUsage { provider, model, .. }
if provider == "deepseek" && model == "deepseek-v4-pro"
)
});
assert!(reported, "the resolved wire model, not `auto`, is reported");
}
@@ -641,6 +641,7 @@ impl Engine {
job.response_settled(!response_stream_failed);
}
turn.add_parent_usage(&usage);
turn.note_parent_model(&stream_request.model);
turn.note_parent_prompt_len(
self.session.messages.len(),
crate::compaction::estimate_request_input_tokens(
+8
View File
@@ -93,6 +93,9 @@ pub struct TurnContext {
/// their own routed receipts.
pub parent_route_usage: Usage,
/// Model the most recent parent-route request was dispatched with.
pub last_parent_model: Option<String>,
/// Provider calls whose usage became ambiguous after dispatch (for
/// example an RLM timeout). A non-zero value makes cost coverage
/// explicitly incomplete instead of inventing a zero-usage receipt.
@@ -199,6 +202,7 @@ impl TurnContext {
..Usage::default()
},
parent_route_usage: Usage::default(),
last_parent_model: None,
routed_usage_dropped_records: 0,
latest_parent_input_tokens: None,
messages_len_at_last_parent_prompt: None,
@@ -275,6 +279,10 @@ impl TurnContext {
add_usage_to(&mut self.parent_route_usage, usage);
}
pub fn note_parent_model(&mut self, model: &str) {
self.last_parent_model = Some(model.to_string());
}
pub fn add_routed_usage_dropped_records(&mut self, dropped_records: u64) {
self.routed_usage_dropped_records = self
.routed_usage_dropped_records
+30
View File
@@ -1363,6 +1363,36 @@ fn auto_route_usage_has_reported_data(usage: &codewhale_models::Usage) -> bool {
|| usage.server_tool_use.is_some()
}
/// Stable, persistence-safe identity for one classifier response. The raw
/// provider response id is hashed with the frozen dispatch route and instant;
/// neither it nor any custom route label crosses into telemetry/persistence.
pub fn auto_route_usage_source_id(route: &EffectiveRouteEnvelope, response_id: &str) -> String {
use sha2::{Digest as _, Sha256};
let mut digest = Sha256::new();
let dispatched_at = route.dispatched_at.to_rfc3339();
for part in [
b"codewhale:auto-route-classifier:v1".as_slice(),
route.provider.as_str().as_bytes(),
route.provider_identity.as_bytes(),
route.model.as_bytes(),
route
.endpoint_fingerprint
.as_deref()
.unwrap_or_default()
.as_bytes(),
dispatched_at.as_bytes(),
response_id.as_bytes(),
] {
digest.update((part.len() as u64).to_le_bytes());
digest.update(part);
}
format!(
"auto-router:{}",
codewhale_runtime::hashing::hex_bytes(digest.finalize())
)
}
fn auto_route_attempt_from_response(
_request_route: EffectiveRouteEnvelope,
response: &MessageResponse,
+3 -3
View File
@@ -226,10 +226,10 @@
"TranscriptReasoningExpand": "expand",
"TranscriptThought": "Thought",
"TranscriptThoughtFor": "Thought for {duration}",
"TelemetryNoticeDefaultOn": "Usage reporting is on by default. Share aggregate version/platform, session, feature and error counts with Codewhale and PostHog (processor). Also counts providers, public catalog models, token totals and built-in tool use. No content or IP. docs/TELEMETRY.md Turn off: codewhale config set telemetry false",
"TelemetryNoticeDefaultOn": "Usage reporting is on by default. Share aggregate version/platform, session, feature and error counts with Codewhale and PostHog (processor). Also counts providers, public catalog models, token totals, request counts, model wait time, prompt-size ranges, built-in tool use, how an exec session started and a coarse install-age range. No content or IP. docs/TELEMETRY.md Turn off: codewhale config set telemetry false",
"TelemetryNoticeHeadline": "Codewhale usage reporting",
"TelemetryNoticeBody": "Codewhale counts: which version you run, OS and CPU family, session\nduration and outcome, and aggregate feature and error counters.\n\nIt also counts the providers and public catalog models you use, their\ntoken totals, and how often each built-in tool runs.\n\nIt never collects your conversations, code, prompts, files, repo or\nbranch names, model content, or credentials — and it never sends a\nper-turn or per-tool timeline of agent activity.\n\nYou are identified only by a random ID stored on this machine, replaced\nevery 90 days. Change your mind any time:\n codewhale config set telemetry false\n\nFull schema, field by field: docs/TELEMETRY.md\n\nUsage reporting is on by default. Codewhale and PostHog process these counts when delivery is configured. No IP is collected.",
"TelemetryNoticeCompactBody": "Counts: version, OS/CPU, session\ntime/result, feature/error totals.\nAlso: provider/model, tokens, tools.\nRandom local ID rotates every 90d.\nNever: chat/code/prompts/files/names;\nmodel content/credentials; turn/tools.\nSchema: docs/TELEMETRY.md\nOff: codewhale config set telemetry\nfalse\nUsage reporting is on by default. Codewhale and PostHog process these counts when delivery is configured. No IP is collected.",
"TelemetryNoticeBody": "Codewhale counts: which version you run, OS and CPU family, session\nduration and outcome, and aggregate feature and error counters.\n\nIt also counts the providers and public catalog models you use, their\ntoken totals, request counts, time spent waiting on the model and\nprompt-size ranges, how often each built-in tool runs, how an exec\nsession was started, and a coarse install-age range.\n\nIt never collects your conversations, code, prompts, files, repo or\nbranch names, model content, or credentials — and it never sends a\nper-turn or per-tool timeline of agent activity.\n\nYou are identified only by a random ID stored on this machine, replaced\nevery 90 days. Change your mind any time:\n codewhale config set telemetry false\n\nFull schema, field by field: docs/TELEMETRY.md\n\nUsage reporting is on by default. Codewhale and PostHog process these counts when delivery is configured. No IP is collected.",
"TelemetryNoticeCompactBody": "Counts: version, OS/CPU, session\ntime/result, feature/error totals.\nAlso: provider/model, tokens, tools,\nrequests, wait time, prompt-size and\ninstall-age ranges, exec start.\nRandom local ID rotates every 90d.\nNever: chat/code/prompts/files/names;\nmodel content/credentials; turn/tools.\nSchema: docs/TELEMETRY.md\nOff: codewhale config set telemetry\nfalse\nUsage reporting is on by default. Codewhale and PostHog process these counts when delivery is configured. No IP is collected.",
"TelemetryNoticeChoiceKeep": "Yes, keep anonymous counts",
"TelemetryNoticeChoiceDisable": "No, turn off tracking",
"TelemetryNoticeActionChoose": "choose",
+2 -1
View File
@@ -135,7 +135,8 @@ pub const MATRIX_BORDER_RGB: (u8, u8, u8) = (0, 204, 0); // #00CC00
// whale's ivory ink on both sides. This is the charcoal alternative to the
// terminal's navy "Underwater" default in 0.10.0. The
// 0.10.0 action pair uses glacial blue on charcoal and deep ocean blue on
// paper.
// paper. The GPUI desktop does not paint these values: its theme is the
// separate `GPUI_*` / `GPUI_LIGHT_*` set below.
//
// Every pair audited by `contrast::theme_contrast_violations` clears its
// floor: body roles clear 4.5:1 on all four surfaces, hint/dim and the
+10
View File
@@ -91,6 +91,16 @@ pub fn codewhale_home_is_explicit() -> bool {
path_env("CODEWHALE_HOME").is_some()
}
/// Return the legacy `DEEPSEEK_HOME` compatibility override, if configured.
///
/// New state must use [`codewhale_home`]. This resolver exists only for readers
/// whose persisted format still explicitly supports the legacy environment
/// alias.
#[must_use]
pub fn legacy_deepseek_home_override() -> Option<PathBuf> {
path_env("DEEPSEEK_HOME")
}
/// Resolve the user's platform home, preferring `HOME` before `USERPROFILE`.
///
/// The explicit environment order makes CLI, state, config, and secret paths
+3
View File
@@ -10,6 +10,9 @@ description = "Codewhale sandboxed Python REPL runtime"
[lints]
workspace = true
[features]
test-support = []
[dependencies]
codewhale-dependencies = { path = "../dependencies", version = "0.10.3" }
codewhale-runtime = { path = "../runtime", version = "0.10.3" }
+1
View File
@@ -80,6 +80,7 @@ uuid.workspace = true
wait-timeout = "0.2"
[dev-dependencies]
futures-util = "0.3"
ring = "0.17"
wiremock = "0.6"
codewhale-models = { path = "../models", version = "0.10.3", features = [
+1
View File
@@ -344,6 +344,7 @@ mod tests {
};
handle.record(Event::SessionStart {
source: crate::SessionSource::Unknown,
install_age: None,
});
let waiter = std::thread::spawn(move || handle.persist_local());
assert!(matches!(rx.try_recv(), Ok(Message::Event(_))));
+4 -1
View File
@@ -10,7 +10,7 @@
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
use crate::event::{Counters, Errors, Event, ModelCounters, TurnWall};
use crate::event::{ContextSize, Counters, Errors, Event, ModelCounters, TurnWall};
/// One session's accumulated counts.
#[derive(Debug, Default)]
@@ -48,6 +48,7 @@ struct ModelSlot {
model: String,
counters: ModelCounters,
turn_wall: TurnWall,
context: ContextSize,
}
/// At most this many distinct provider and model pairs per session; later
@@ -186,6 +187,7 @@ impl SessionCounters {
model,
counters: ModelCounters::default(),
turn_wall: TurnWall::default(),
context: ContextSize::default(),
});
models.len() - 1
}
@@ -238,6 +240,7 @@ impl SessionCounters {
model: slot.model.clone(),
counters: slot.counters,
turn_wall: slot.turn_wall,
context: slot.context,
}));
}
if let Ok(tools) = self.tools.lock() {
+72 -1
View File
@@ -6,7 +6,7 @@ use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::buffer;
use crate::event::{Arch, Libc, Os};
use crate::event::{Arch, InstallAge, Libc, Os};
/// How long an install id may live before it is replaced.
///
@@ -47,6 +47,77 @@ pub struct TelemetryState {
/// a permanently offline machine tries at most once per interval.
#[serde(default)]
pub last_flush: Option<String>,
/// The UTC day (`YYYY-MM-DD`) this state was first created. Local only: it
/// is read to pick an [`InstallAge`] bucket and is never sent.
#[serde(default)]
pub first_seen_day: Option<String>,
/// Set when this file predates `first_seen_day`, so its age is unknown and
/// is reported as the oldest bucket rather than as new.
#[serde(default)]
pub first_seen_unknown: bool,
}
enum StateRead {
Missing,
Unreadable,
Present(TelemetryState),
}
fn read_state_checked(root: &Path) -> StateRead {
match std::fs::read_to_string(buffer::state_path(root)) {
Ok(body) => serde_json::from_str::<TelemetryState>(&body)
.map_or(StateRead::Unreadable, StateRead::Present),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => StateRead::Missing,
Err(_) => StateRead::Unreadable,
}
}
/// Today's date in UTC.
#[must_use]
pub fn utc_today() -> chrono::NaiveDate {
chrono::Utc::now().date_naive()
}
/// Record the first-seen day if this state has none. A missing state file is a
/// new install; a file that has a recorded version but no day predates this
/// field and is marked unknown. An unreadable file is left untouched.
pub(crate) fn stamp_first_seen(root: &Path, today: chrono::NaiveDate) {
let mut state = match read_state_checked(root) {
StateRead::Unreadable => return,
StateRead::Missing => TelemetryState::default(),
StateRead::Present(state) => state,
};
if state.first_seen_day.is_some() || state.first_seen_unknown {
return;
}
if state.last_version.is_some() {
state.first_seen_unknown = true;
} else {
state.first_seen_day = Some(today.format("%Y-%m-%d").to_string());
}
let _ = write_state(root, &state);
}
/// The coarse age bucket for this installation, or `None` when the local state
/// cannot be read. A missing state is new.
pub(crate) fn install_age_at(root: &Path, today: chrono::NaiveDate) -> Option<InstallAge> {
let state = match read_state_checked(root) {
StateRead::Unreadable => return None,
StateRead::Missing => return Some(InstallAge::NewToday),
StateRead::Present(state) => state,
};
if state.first_seen_unknown {
return Some(InstallAge::Older);
}
let Some(day) = state.first_seen_day else {
return Some(InstallAge::NewToday);
};
let first = chrono::NaiveDate::parse_from_str(&day, "%Y-%m-%d").ok()?;
Some(match today.signed_duration_since(first).num_days() {
..=0 => InstallAge::NewToday,
1..=6 => InstallAge::UnderWeek,
_ => InstallAge::Older,
})
}
/// Read the install id, minting a fresh one if it is missing, unreadable,
+122 -26
View File
@@ -33,10 +33,10 @@ use serde::{Deserialize, Serialize};
/// Wire schema version. Bumped on any field add, remove, or retype; never
/// reused. `crates/telemetry/tests/golden/v1.json` pins what v1 was.
pub const SCHEMA_VERSION: u32 = 4;
pub const SCHEMA_VERSION: u32 = 6;
/// Default-on policy disclosure version. This is not human consent.
pub const NOTICE_VERSION: u32 = 6;
pub const NOTICE_VERSION: u32 = 8;
/// Which product surface produced a batch.
///
@@ -277,6 +277,12 @@ pub enum SessionSource {
/// Started under CI (`CI` or `GITHUB_ACTIONS` set), including the GitHub
/// Action, so automation is never counted as a person.
Ci,
/// `exec` started by Codewhale's own fleet dispatcher.
FleetWorker,
/// `exec` started from inside an agent's shell command.
Agent,
/// `exec` whose stdin or stdout is not a terminal.
Scripted,
}
impl SessionSource {
@@ -288,6 +294,9 @@ impl SessionSource {
Self::Api,
Self::Unknown,
Self::Ci,
Self::FleetWorker,
Self::Agent,
Self::Scripted,
];
/// The wire spelling.
@@ -300,6 +309,37 @@ impl SessionSource {
Self::Api => "api",
Self::Unknown => "unknown",
Self::Ci => "ci",
Self::FleetWorker => "fleet_worker",
Self::Agent => "agent",
Self::Scripted => "scripted",
}
}
}
/// How long this install has existed, as a coarse bucket. The first-seen date
/// itself never leaves the device.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InstallAge {
/// First seen on the current UTC day.
NewToday,
/// First seen 1 to 6 UTC days ago.
UnderWeek,
/// First seen 7 or more UTC days ago, or before the date was recorded.
Older,
}
impl InstallAge {
/// Every value, for exhaustive iteration.
pub const ALL: &'static [Self] = &[Self::NewToday, Self::UnderWeek, Self::Older];
/// The wire spelling.
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NewToday => "new_today",
Self::UnderWeek => "under_week",
Self::Older => "older",
}
}
}
@@ -366,11 +406,20 @@ pub enum ExitClass {
Panic,
/// Exited non-successfully without a signal or a panic.
Error,
/// The process ended without its shutdown report; its aggregates were
/// recovered from a local checkpoint at a later start.
Unclean,
}
impl ExitClass {
/// Every value, for exhaustive iteration.
pub const ALL: &'static [Self] = &[Self::Clean, Self::Signal, Self::Panic, Self::Error];
pub const ALL: &'static [Self] = &[
Self::Clean,
Self::Signal,
Self::Panic,
Self::Error,
Self::Unclean,
];
/// The wire spelling.
#[must_use]
@@ -380,6 +429,7 @@ impl ExitClass {
Self::Signal => "signal",
Self::Panic => "panic",
Self::Error => "error",
Self::Unclean => "unclean",
}
}
@@ -391,6 +441,7 @@ impl ExitClass {
Self::Signal => 1,
Self::Panic => 2,
Self::Error => 3,
Self::Unclean => 4,
}
}
@@ -401,6 +452,7 @@ impl ExitClass {
1 => Self::Signal,
2 => Self::Panic,
3 => Self::Error,
4 => Self::Unclean,
_ => Self::Clean,
}
}
@@ -639,6 +691,9 @@ pub enum Event {
SessionStart {
/// How it was started.
source: SessionSource,
/// Coarse install age. `null` when the local state cannot be read.
#[serde(default)]
install_age: Option<InstallAge>,
},
/// A session ended. Everything the session accumulated ships here, once.
SessionEnd {
@@ -696,6 +751,9 @@ pub enum Event {
counters: ModelCounters,
/// Turn wall-clock buckets for these turns.
turn_wall: TurnWall,
/// Requests by input size.
#[serde(default)]
context: ContextSize,
},
/// One session's calls of one tool.
ToolUsage {
@@ -725,6 +783,16 @@ pub struct ModelCounters {
pub cache_read_tokens: u64,
/// Input tokens written to the provider's prompt cache.
pub cache_write_tokens: u64,
/// Provider requests on the session's own route for this model.
#[serde(default)]
pub requests: u32,
/// Reasoning tokens as the provider reports them; a subset of
/// `output_tokens`, which is not reduced.
#[serde(default)]
pub reasoning_tokens: u64,
/// Whole seconds spent waiting on the model, summed over the session.
#[serde(default)]
pub generation_secs: u32,
}
impl ModelCounters {
@@ -737,9 +805,44 @@ impl ModelCounters {
"output_tokens",
"cache_read_tokens",
"cache_write_tokens",
"requests",
"reasoning_tokens",
"generation_secs",
];
}
/// Per-session count of model requests by input size, in tokens including
/// cache reads. Half-open intervals; K is 1024. A histogram, never a
/// per-request series.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContextSize {
/// Requests with `[0, 32768)` input tokens.
pub lt_32k: u32,
/// Requests with `[32768, 131072)` input tokens.
#[serde(rename = "32k_128k")]
pub k32_to_k128: u32,
/// Requests with `[131072, 262144)` input tokens.
#[serde(rename = "128k_256k")]
pub k128_to_k256: u32,
/// Requests with 262144 or more input tokens.
pub gte_256k: u32,
}
impl ContextSize {
/// Field names in wire spelling, in declaration order.
pub const FIELDS: &'static [&'static str] = &["lt_32k", "32k_128k", "128k_256k", "gte_256k"];
/// Record one request with `tokens` input tokens.
pub fn observe(&mut self, tokens: u64) {
match tokens {
0..32_768 => self.lt_32k = self.lt_32k.saturating_add(1),
32_768..131_072 => self.k32_to_k128 = self.k32_to_k128.saturating_add(1),
131_072..262_144 => self.k128_to_k256 = self.k128_to_k256.saturating_add(1),
_ => self.gte_256k = self.gte_256k.saturating_add(1),
}
}
}
/// First-party tool names reported by `tool_usage`. Any other name is
/// reported as `mcp` or `other`, so a plugin's or server's tool name never
/// leaves the machine.
@@ -830,17 +933,22 @@ pub fn is_reported_tool_name(value: &str) -> bool {
value == "mcp" || value == "other" || TOOL_NAMES.contains(&value)
}
/// The `model` value for a model id: the lowercased id when the bundled model
/// catalog lists it, otherwise `other`. Custom, local and fine-tuned model
/// names therefore never leave the machine.
/// The `model` value for a model id: the lowercased canonical id when the
/// bundled model catalog lists it, otherwise `other`. Official aliases and
/// compatibility spellings are resolved first. Custom, local and fine-tuned
/// model names therefore never leave the machine.
#[must_use]
pub fn reported_model_id(model: &str) -> String {
use codewhale_config::catalog::reviewed::{compatibility_alias, official_deepseek_model_id};
let id = model.trim().to_ascii_lowercase();
if is_catalogued_model(&id) {
id
} else {
"other".to_string()
}
let canonical = official_deepseek_model_id(&id)
.or_else(|| compatibility_alias("canonical_model_name", &id))
.map(str::to_ascii_lowercase);
canonical
.into_iter()
.chain(std::iter::once(id))
.find(|candidate| is_catalogued_model(candidate))
.unwrap_or_else(|| "other".to_string())
}
/// Whether `value` may appear as `model_usage.model`.
@@ -850,21 +958,9 @@ pub fn is_reported_model_id(value: &str) -> bool {
}
fn is_catalogued_model(id: &str) -> bool {
if id.is_empty() || id.len() > 128 {
return false;
}
let catalog = codewhale_config::catalog::bundled_models_dev_catalog();
catalog.reviewed.intrinsic.contains_key(id)
|| catalog
.models
.keys()
.any(|key| key.eq_ignore_ascii_case(id))
|| catalog.providers.values().any(|provider| {
provider
.models
.keys()
.any(|key| key.eq_ignore_ascii_case(id))
})
!id.is_empty()
&& id.len() <= 128
&& codewhale_config::catalog::reviewed::public_model_identifier_ignore_case(id)
}
impl Event {
+12 -3
View File
@@ -57,9 +57,9 @@ pub use decision::{
};
pub use envelope::reduce_panic_site;
pub use event::{
Arch, Batch, ColdStartBucket, Counters, DurationBucket, Errors, Event, ExitClass, InstallKind,
Libc, ModelCounters, NOTICE_VERSION, Os, ProductCounters, SCHEMA_VERSION, SessionSource,
Surface, TurnWall,
Arch, Batch, ColdStartBucket, ContextSize, Counters, DurationBucket, Errors, Event, ExitClass,
InstallAge, InstallKind, Libc, ModelCounters, NOTICE_VERSION, Os, ProductCounters,
SCHEMA_VERSION, SessionSource, Surface, TurnWall,
};
/// How long the shutdown flush may hold the process.
@@ -123,9 +123,18 @@ pub fn init(consent: TelemetryConsent) {
exit_class: AtomicU8::new(ExitClass::Clean.as_u8()),
});
envelope::stamp_first_seen(&root, envelope::utc_today());
record_install_or_upgrade(&root);
}
/// The coarse install-age bucket for this process's `session_start`, or `None`
/// when unarmed or when the local state cannot be read.
#[must_use]
pub fn install_age() -> Option<InstallAge> {
let armed = ARMED.get()?;
envelope::install_age_at(&armed.root, envelope::utc_today())
}
/// Note that this binary's version differs from the one last seen on this
/// machine, at most once per version.
///
+7 -2
View File
@@ -13,6 +13,9 @@
//! Sampling and hashing are not the same promise, and a notice that implies
//! them when neither is true is worse than no notice.
/// Headline shown above [`NOTICE_BODY`].
pub const NOTICE_HEADLINE: &str = "Codewhale usage reporting";
/// The notice itself.
///
/// Wrapped at 72 columns so it renders unchanged in the native responsive
@@ -22,7 +25,9 @@ Codewhale counts: which version you run, OS and CPU family, session
duration and outcome, and aggregate feature and error counters.
It also counts the providers and public catalog models you use, their
token totals, and how often each built-in tool runs.
token totals, request counts, time spent waiting on the model and
prompt-size ranges, how often each built-in tool runs, how an exec
session was started, and a coarse install-age range.
It never collects your conversations, code, prompts, files, repo or
branch names, model content, or credentials — and it never sends a
@@ -38,7 +43,7 @@ Usage reporting is on by default. Codewhale and PostHog process these
counts when delivery is configured. No IP is collected.";
/// Concise disclosure for every armed runtime surface, including headless CLI.
pub const STARTUP_DISCLOSURE: &str = "Usage reporting is on by default: Codewhale and PostHog process aggregate version/platform, session, feature, error, model/token and built-in tool counts when delivery is configured. No content or IP. Turn off: codewhale config set telemetry false. Details: codewhale config telemetry";
pub const STARTUP_DISCLOSURE: &str = "Usage reporting is on by default: Codewhale and PostHog process aggregate version/platform, session, feature, error, model/token/request/wait-time/prompt-size, exec-start, install-age range and built-in tool counts when delivery is configured. No content or IP. Turn off: codewhale config set telemetry false. Details: codewhale config telemetry";
/// Present the policy once per revision without recording human acceptance.
/// Failure to save the display marker only causes a later repeat disclosure.
+322 -11
View File
@@ -121,11 +121,12 @@ fn every_event() -> Vec<Event> {
previous_version: Some("0.9.3-rc.1".to_string()),
},
Event::SessionStart {
source: SessionSource::Resume,
source: SessionSource::FleetWorker,
install_age: Some(InstallAge::UnderWeek),
},
Event::SessionEnd {
duration_bucket: DurationBucket::OneToTen,
exit_class: ExitClass::Panic,
exit_class: ExitClass::Unclean,
cold_start_bucket: Some(ColdStartBucket::Mid),
providers: vec!["custom".to_string(), "deepseek".to_string()],
counters: Counters {
@@ -183,6 +184,9 @@ fn every_event() -> Vec<Event> {
output_tokens: 9_120,
cache_read_tokens: 380_001,
cache_write_tokens: 0,
requests: 27,
reasoning_tokens: 2_310,
generation_secs: 412,
},
turn_wall: TurnWall {
lt_5s: 3,
@@ -190,6 +194,12 @@ fn every_event() -> Vec<Event> {
thirty_to_onetwenty: 2,
gte_120s: 0,
},
context: ContextSize {
lt_32k: 9,
k32_to_k128: 11,
k128_to_k256: 5,
gte_256k: 2,
},
},
Event::ToolUsage {
tool: "read_file".to_string(),
@@ -269,6 +279,7 @@ fn closed_enum_values() -> Vec<String> {
values.extend(Libc::ALL.iter().map(|v| v.as_str().to_string()));
values.extend(InstallKind::ALL.iter().map(|v| v.as_str().to_string()));
values.extend(SessionSource::ALL.iter().map(|v| v.as_str().to_string()));
values.extend(InstallAge::ALL.iter().map(|v| v.as_str().to_string()));
values.extend(DurationBucket::ALL.iter().map(|v| v.as_str().to_string()));
values.extend(ExitClass::ALL.iter().map(|v| v.as_str().to_string()));
values.extend(ColdStartBucket::ALL.iter().map(|v| v.as_str().to_string()));
@@ -1226,6 +1237,7 @@ fn probe_threshold_cannot_hide_an_over_cap_buffer() {
// only safe if `MAX_EVENTS` lines cannot fit under it.
let shortest = serde_json::to_string(&Event::SessionStart {
source: SessionSource::Api,
install_age: None,
})
.expect("serialize");
let floor = (shortest.len() as u64 + 1) * buffer::MAX_EVENTS as u64;
@@ -1446,6 +1458,7 @@ fn record_blocking_is_a_noop_when_unarmed() {
});
crate::record(Event::SessionStart {
source: SessionSource::Interactive,
install_age: None,
});
crate::set_exit_class(ExitClass::Panic);
assert_eq!(crate::exit_class(), ExitClass::Clean);
@@ -1659,6 +1672,7 @@ fn no_public_api_accepts_a_bare_bool() {
const TELEMETRY_DOC: &str = include_str!("../../../docs/TELEMETRY.md");
const GOLDEN_V4: &str = include_str!("../tests/golden/v4.json");
const GOLDEN_V6: &str = include_str!("../tests/golden/v6.json");
/// Extract the fenced ```jsonc blocks from the schema doc, in order.
fn jsonc_blocks(doc: &str) -> Vec<String> {
@@ -1864,13 +1878,12 @@ fn event_field_names_match_documented_schema() {
}
#[test]
fn golden_payload_v4() {
fn golden_payload_v6() {
assert_eq!(NOTICE_VERSION.to_string(), TELEMETRY_NOTICE_VERSION);
// `crates/telemetry/tests/golden/v4.json` is one fully-populated instance of
// the envelope and every event. Any field add, remove, or retype fails here
// until the developer re-blesses it under a bumped `SCHEMA_VERSION` — and it
// is also the artifact a future receiver author reads to know exactly what
// v1 was.
// `crates/telemetry/tests/golden/v6.json` is one fully-populated instance of
// the envelope and every event, and the batch the collector's own tests
// post. Any field add, remove, or retype fails here until the developer
// re-blesses it under a bumped `SCHEMA_VERSION`.
//
// Re-bless with: `CODEWHALE_BLESS_TELEMETRY_GOLDEN=1 cargo test -p codewhale-telemetry`
let batch = every_field_batch();
@@ -1878,22 +1891,81 @@ fn golden_payload_v4() {
batch.schema_version, SCHEMA_VERSION,
"the fixture must be built at the current schema version"
);
assert_eq!(SCHEMA_VERSION, 6);
let mut rendered = serde_json::to_string_pretty(&batch).expect("serialize");
rendered.push('\n');
if std::env::var("CODEWHALE_BLESS_TELEMETRY_GOLDEN").is_ok() {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/v4.json");
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/v6.json");
std::fs::create_dir_all(path.parent().expect("parent")).expect("create golden dir");
std::fs::write(&path, &rendered).expect("write golden");
return;
}
assert_eq!(
rendered, GOLDEN_V4,
"the v4 payload changed; bump SCHEMA_VERSION and re-bless the golden file"
rendered, GOLDEN_V6,
"the v6 payload changed; bump SCHEMA_VERSION and re-bless the golden file"
);
}
#[test]
fn the_schema_4_golden_still_reads_back_with_the_new_fields_defaulted() {
let legacy: Batch = serde_json::from_str(GOLDEN_V4).expect("v4 golden parses");
assert_eq!(legacy.schema_version, 4);
for event in &legacy.events {
match event {
Event::SessionStart { install_age, .. } => assert_eq!(*install_age, None),
Event::ModelUsage {
counters, context, ..
} => {
assert_eq!(counters.requests, 0);
assert_eq!(counters.reasoning_tokens, 0);
assert_eq!(counters.generation_secs, 0);
assert_eq!(*context, ContextSize::default());
}
_ => {}
}
}
}
#[test]
fn context_buckets_are_half_open_at_32k_128k_and_256k() {
let mut size = ContextSize::default();
for tokens in [
0,
32_767,
32_768,
131_071,
131_072,
262_143,
262_144,
u64::MAX,
] {
size.observe(tokens);
}
assert_eq!(
size,
ContextSize {
lt_32k: 2,
k32_to_k128: 2,
k128_to_k256: 2,
gte_256k: 2,
}
);
let json = serde_json::to_value(size).expect("serialize");
let keys: Vec<&str> = json
.as_object()
.expect("object")
.keys()
.map(String::as_str)
.collect();
let mut expected: Vec<&str> = ContextSize::FIELDS.to_vec();
expected.sort_unstable();
let mut got = keys;
got.sort_unstable();
assert_eq!(got, expected);
}
#[test]
fn version_comparison_names_install_upgrade_and_downgrade() {
assert!(crate::version_is_older("0.9.3", "0.9.4"));
@@ -1994,3 +2066,242 @@ fn the_notice_summarizes_what_the_schema_collects_and_states_every_red_line() {
assert!(!body.contains("CODEWHALE_TELEMETRY=0"));
assert!(body.contains("docs/TELEMETRY.md"));
}
// ------------------------------------------------------------- model naming --
fn model_id_is_collector_shaped(id: &str) -> bool {
let bytes = id.as_bytes();
(1..=128).contains(&bytes.len())
&& bytes[0].is_ascii_lowercase() | bytes[0].is_ascii_digit()
&& bytes[1..].iter().all(|b| {
b.is_ascii_lowercase()
|| b.is_ascii_digit()
|| matches!(b, b'.' | b'_' | b':' | b'/' | b'@' | b'+' | b'-')
})
}
#[test]
fn reported_model_id_resolves_aliases_and_spellings() {
assert_eq!(reported_model_id("deepseek-v4-pro"), "deepseek-v4-pro");
assert_eq!(reported_model_id(" DeepSeek-V4-Pro "), "deepseek-v4-pro");
assert_eq!(reported_model_id("deepseek-v4pro"), "deepseek-v4-pro");
assert_eq!(
reported_model_id("deepseek-ai/deepseek-v4-pro"),
"deepseek-v4-pro"
);
assert_eq!(
reported_model_id("deepseek/deepseek-v4pro"),
"deepseek-v4-pro"
);
assert_eq!(reported_model_id("pro"), "deepseek-v4-pro");
assert_eq!(reported_model_id("flash"), "deepseek-flash");
assert_eq!(reported_model_id("auto"), "other");
assert_eq!(reported_model_id("my-private-finetune"), "other");
assert_eq!(reported_model_id(""), "other");
}
#[test]
fn reported_model_id_never_leaves_the_catalog() {
use codewhale_config::catalog::reviewed::{
bundled_reviewed, public_model_identifier_ignore_case,
};
let reviewed = bundled_reviewed();
let mut spellings: Vec<&str> = reviewed
.official_deepseek_aliases
.keys()
.chain(reviewed.go_aliases.keys())
.map(String::as_str)
.collect();
if let Some(group) = reviewed.compatibility_aliases.get("canonical_model_name") {
spellings.extend(group.keys().map(String::as_str));
}
assert!(spellings.len() > 20, "alias tables look empty");
for spelling in spellings {
let reported = reported_model_id(spelling);
assert!(is_reported_model_id(&reported), "{spelling} -> {reported}");
assert!(
model_id_is_collector_shaped(&reported),
"{spelling} -> {reported}"
);
}
for hostile in ["", "x/../y", "deepseek-v4-pro\n", "Ünï", &"a".repeat(300)] {
let reported = reported_model_id(hostile);
assert!(
reported == "other" || public_model_identifier_ignore_case(&reported),
"{hostile:?} -> {reported}"
);
}
}
#[test]
fn every_listed_model_and_provider_default_maps_to_a_catalogued_id() {
let catalog = codewhale_config::catalog::bundled_models_dev_catalog();
let mut missing = Vec::new();
let mut check = |origin: &str, id: &str| {
let reported = reported_model_id(id);
if reported == "other" || !model_id_is_collector_shaped(&reported) {
missing.push(format!("{origin}: {id}"));
}
};
for provider in catalog.providers.values() {
for (id, row) in &provider.models {
check("catalog", id);
check("catalog row", &row.id);
}
}
for id in catalog.models.keys() {
check("canonical", id);
}
let descriptors: Value = serde_json::from_str(
&std::fs::read_to_string(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../config/assets/provider_descriptors.json"),
)
.expect("provider descriptors"),
)
.expect("descriptors json");
let exceptions: &[&str] = &["antigravity", "custom", "openai-compatible", "ollama"];
for provider in descriptors["providers"].as_array().expect("providers") {
let id = provider["id"].as_str().expect("provider id");
let selectable = provider["selectable"].as_bool().unwrap_or(false);
let default = provider["default_model"].as_str().unwrap_or_default();
if selectable && !default.is_empty() && !exceptions.contains(&id) {
check(&format!("default for {id}"), default);
}
}
assert!(
missing.is_empty(),
"ids the catalog does not name:\n{}",
missing.join("\n")
);
}
// -------------------------------------------------------------- install age --
fn day(text: &str) -> chrono::NaiveDate {
chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d").expect("date")
}
fn root_with_state(state: &str) -> (tempfile::TempDir, PathBuf) {
let home = temp_home();
let root = root_of(&home);
buffer::ensure_dir(&root).expect("create telemetry dir");
std::fs::write(buffer::state_path(&root), state).expect("write state");
(home, root)
}
#[test]
fn a_fresh_home_is_new_today_and_ages_by_utc_day() {
let home = temp_home();
let root = root_of(&home);
buffer::ensure_dir(&root).expect("create telemetry dir");
assert_eq!(
envelope::install_age_at(&root, day("2026-11-13")),
Some(InstallAge::NewToday)
);
envelope::stamp_first_seen(&root, day("2026-11-13"));
for (today, expected) in [
("2026-11-13", InstallAge::NewToday),
("2026-11-14", InstallAge::UnderWeek),
("2026-11-16", InstallAge::UnderWeek),
("2026-11-19", InstallAge::UnderWeek),
("2026-11-20", InstallAge::Older),
("2027-06-01", InstallAge::Older),
("2026-11-12", InstallAge::NewToday),
] {
assert_eq!(
envelope::install_age_at(&root, day(today)),
Some(expected),
"{today}"
);
}
envelope::stamp_first_seen(&root, day("2026-12-25"));
assert_eq!(
envelope::read_state(&root).first_seen_day.as_deref(),
Some("2026-11-13"),
"a second stamp never moves the first-seen day"
);
}
#[test]
fn a_state_written_before_the_day_existed_reads_older_never_new() {
let (_home, root) = root_with_state(r#"{"schema_version":4,"last_version":"0.10.2"}"#);
envelope::stamp_first_seen(&root, day("2026-11-13"));
let state = envelope::read_state(&root);
assert_eq!(state.first_seen_day, None);
assert!(state.first_seen_unknown);
assert_eq!(state.last_version.as_deref(), Some("0.10.2"));
for today in ["2026-11-13", "2026-11-14", "2030-01-01"] {
assert_eq!(
envelope::install_age_at(&root, day(today)),
Some(InstallAge::Older),
"{today}"
);
}
}
#[test]
fn unreadable_or_hostile_state_gives_null_and_is_not_overwritten() {
for body in [
"not json",
r#"{"first_seen_day":"9999-99-99"}"#,
r#"{"first_seen_day":"yesterday"}"#,
] {
let (_home, root) = root_with_state(body);
envelope::stamp_first_seen(&root, day("2026-11-13"));
assert_eq!(
envelope::install_age_at(&root, day("2026-11-13")),
None,
"{body}"
);
assert_eq!(
std::fs::read_to_string(buffer::state_path(&root)).expect("state"),
body,
"{body}"
);
}
}
#[test]
fn opting_out_erases_the_age_and_rotating_the_install_id_keeps_it() {
let home = temp_home();
let root = root_of(&home);
buffer::ensure_dir(&root).expect("create telemetry dir");
envelope::stamp_first_seen(&root, day("2026-01-01"));
assert_eq!(
envelope::install_age_at(&root, day("2026-11-13")),
Some(InstallAge::Older)
);
std::fs::write(
buffer::install_id_path(&root),
r#"{"schema_version":1,"install_id":"3f2a9c1e-0000-4000-8000-000000000001","rotated_at":"2020-01-01T00:00:00Z"}"#,
)
.expect("write expired id");
let rotated = envelope::read_or_create_install_id(&root).expect("rotate");
assert_ne!(rotated.install_id, "3f2a9c1e-0000-4000-8000-000000000001");
assert_eq!(
envelope::read_state(&root).first_seen_day.as_deref(),
Some("2026-01-01"),
"rotation does not touch the age"
);
buffer::wipe(&root).expect("wipe");
std::fs::remove_file(buffer::tombstone_path(&root)).expect("re-enable");
assert_eq!(
envelope::install_age_at(&root, day("2026-11-13")),
Some(InstallAge::NewToday)
);
envelope::stamp_first_seen(&root, day("2026-11-13"));
assert_eq!(
envelope::read_state(&root).first_seen_day.as_deref(),
Some("2026-11-13")
);
}
#[test]
fn the_first_seen_day_never_reaches_the_wire() {
let wire = serde_json::to_string(&every_field_batch()).expect("serialize");
assert!(!wire.contains("first_seen"));
}
+127
View File
@@ -0,0 +1,127 @@
{
"schema_version": 6,
"notice_version": 8,
"sent_at": "2026-08-03T18:04:11Z",
"install_id": "3f2a9c1e-0000-4000-8000-000000000001",
"app_version": "0.9.4",
"git_sha": "abcdef012345",
"surface": "control-plane",
"os": "macos",
"arch": "aarch64",
"libc": "none",
"tty": true,
"events": [
{
"event": "install_or_upgrade",
"kind": "upgrade",
"previous_version": "0.9.3-rc.1"
},
{
"event": "session_start",
"source": "fleet_worker",
"install_age": "under_week"
},
{
"event": "session_end",
"duration_bucket": "1m_10m",
"exit_class": "unclean",
"cold_start_bucket": "250_1000",
"providers": [
"custom",
"deepseek"
],
"counters": {
"turns": 14,
"tool_calls": 61,
"fleet_dispatch": 0,
"workflow_run": 0,
"subagent_spawn": 2,
"mcp_server_connected": 0,
"memory_search": 0,
"approval_modal_shown": 0,
"approval_auto_allowed": 0,
"command_palette_open": 3
},
"errors": {
"auth_preflight_failed": 0,
"provider_http_4xx": 0,
"provider_http_5xx": 1,
"tool_denied_by_policy": 0,
"tool_timeout": 0,
"network_error": 0
},
"turn_wall": {
"lt_5s": 9,
"5_30s": 4,
"30_120s": 1,
"gte_120s": 0
}
},
{
"event": "panic",
"site": "crates/tui/src/tui/ui.rs:8801:17"
},
{
"event": "product_usage",
"counters": {
"page_view": 1,
"docs_view": 0,
"install_copy": 0,
"download": 0,
"signup": 0,
"login": 0,
"session_create": 0,
"session_resume": 0,
"turn_submit": 0,
"turn_complete": 0,
"settings_open": 0,
"integration_connect": 0,
"error_shown": 0
}
},
{
"event": "operations_summary",
"requests": 10,
"errors": 1,
"duration_ms_total": 1500,
"duration_ms_max": 300,
"probes": 2,
"probes_failed": 0
},
{
"event": "model_usage",
"provider": "deepseek",
"model": "other",
"counters": {
"turns_ok": 12,
"turns_failed": 1,
"turns_interrupted": 0,
"input_tokens": 418230,
"output_tokens": 9120,
"cache_read_tokens": 380001,
"cache_write_tokens": 0,
"requests": 27,
"reasoning_tokens": 2310,
"generation_secs": 412
},
"turn_wall": {
"lt_5s": 3,
"5_30s": 8,
"30_120s": 2,
"gte_120s": 0
},
"context": {
"lt_32k": 9,
"32k_128k": 11,
"128k_256k": 5,
"gte_256k": 2
}
},
{
"event": "tool_usage",
"tool": "read_file",
"calls": 41,
"errors": 2
}
]
}
+4
View File
@@ -197,7 +197,11 @@ codewhale-models = { path = "../models", version = "0.10.3", features = [
cucumber = "0.23.0"
wiremock = "0.6"
tiny_http = "0.12"
pretty_assertions = "1.4"
rio-vt = "0.5.1"
rusqlite.workspace = true
schemars = { version = "1.2.1", features = ["derive", "preserve_order"] }
tokio-tungstenite = "0.30"
codewhale-app-server = { path = "../app-server", version = "0.10.3", features = ["test-support"] }
[target.'cfg(unix)'.dependencies]
+4 -1
View File
@@ -2515,7 +2515,10 @@ fn arm_telemetry_with_setup(
};
codewhale_telemetry::init(consent.with_config_path(Some(store.path().to_path_buf())));
let _ = TELEMETRY_SESSION_START.set(std::time::Instant::now());
codewhale_telemetry::record(codewhale_telemetry::Event::SessionStart { source });
codewhale_telemetry::record(codewhale_telemetry::Event::SessionStart {
source,
install_age: codewhale_telemetry::install_age(),
});
}
fn arm_telemetry(cli: &Cli, command: Option<&Commands>) {
+1
View File
@@ -1285,6 +1285,7 @@ pub enum SidebarRowAction {
Command(String),
/// Put a destructive command in the composer instead of executing it.
/// The user confirms with Enter or cancels by editing/clearing the draft.
#[allow(dead_code)] // destructive confirm path; mouse_ui already matches it (TUI-DOG-008)
PrefillCommand(String),
/// Select the persistent Agents panel. This is deliberately a navigation
/// action rather than a modal: the Subagents summary is a group door, so
+2 -2
View File
@@ -85,7 +85,7 @@ impl BacktrackState {
/// `true` whenever the user has armed or opened backtrack. The UI uses
/// this to skip the prime hint once the overlay is up and to know
/// whether arrow keys should drive selection.
#[cfg(test)]
#[allow(dead_code)] // helper exposed for future UI consumers + tests.
#[must_use]
pub fn is_active(&self) -> bool {
!matches!(self.phase, BacktrackPhase::Inactive)
@@ -94,7 +94,7 @@ impl BacktrackState {
/// `true` only when the overlay is open and Left/Right should step
/// through prior user messages. `Primed` is intentionally excluded —
/// during the prime window arrows still scroll the transcript.
#[cfg(test)]
#[allow(dead_code)] // helper exposed for future UI consumers + tests.
#[must_use]
pub fn is_selecting(&self) -> bool {
matches!(self.phase, BacktrackPhase::Selecting { .. })
+2 -1
View File
@@ -169,6 +169,7 @@ impl LiveTranscriptOverlay {
/// Return the overlay to live-tail mode (used when backtrack is
/// confirmed or canceled). Re-arms sticky-tail so streaming resumes.
#[allow(dead_code)] // exposed for callers that retain an overlay across a backtrack cancel; current UI just pops the view.
pub fn set_tail_mode(&mut self) {
self.mode = Mode::Tail;
self.sticky_to_bottom.set(true);
@@ -176,7 +177,7 @@ impl LiveTranscriptOverlay {
}
/// For tests + UI: current mode.
#[cfg(test)]
#[allow(dead_code)] // currently consumed only by tests; kept public for symmetry with `set_*` setters.
#[must_use]
pub fn mode(&self) -> Mode {
self.mode
+7
View File
@@ -469,6 +469,8 @@ impl WorkflowPlan {
}
}
pub type WorkflowIr = WorkflowPlan;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhasePlan {
pub name: String,
@@ -492,6 +494,8 @@ pub struct Phase {
pub tasks: Vec<Task>,
}
pub type WorkflowPhase = Phase;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum FailurePolicy {
@@ -520,6 +524,9 @@ pub struct Task {
pub timeout_secs: Option<u64>,
}
pub type WorkflowTask = Task;
pub type WorkflowRole = AgentType;
/// The workflow wire's agent type. The serialized spellings are the canonical
/// Codewhale role vocabulary (founder, 2026-09-02); the pre-rename JS
/// spellings stay accepted as aliases so checked-in and saved workflows keep
+4
View File
@@ -65,6 +65,10 @@ impl FleetRoleMap {
self.roles.get(&key).map(String::as_str)
}
pub fn contains_role(&self, role: &str) -> bool {
self.get(role).is_some()
}
pub fn is_empty(&self) -> bool {
self.roles.is_empty()
}
+59 -19
View File
@@ -4,7 +4,7 @@
**Usage analytics are on by default in the current source.** The first
interactive launch gives a localized, nonblocking disclosure naming **Codewhale
and PostHog**, with a direct route to turn counting off. Notice version `6`
and PostHog**, with a direct route to turn counting off. Notice version `8`
describes this policy; displaying it is not recorded as human acceptance.
Missing an older acceptance record does not turn a fresh installation off.
Existing explicit opt-outs remain off across upgrades, and unreadable privacy
@@ -65,7 +65,7 @@ codewhale --telemetry false # the same kill switch, for one command
**`telemetry = false` in the config file is the opt-out.** It is a floor:
`--telemetry true` and `CODEWHALE_TELEMETRY=1` both lose to it, because a
setting you can undo by accident from a wrapper script is not a setting. It
deletes the random install id, truncates every buffered event and every dry-run
deletes the random install id and the local first-seen day (so the install-age bucket starts over at `new_today` if you turn telemetry back on), truncates every buffered event and every dry-run
record, and writes a tombstone. Appends, identity/state writes, and delivery all
share the wipe's ordering lock, so once opt-out returns no pre-opt-out write or
POST remains in flight. If any part of that wipe fails, the tombstone is still
@@ -104,7 +104,7 @@ Everything is under `$CODEWHALE_HOME/telemetry/` (`0700`), every file `0600`:
| `buffer.jsonl` | pending events, one JSON object per line |
| `buffer.jsonl.lock` | the sibling ordering lock shared by writes, delivery, arming, and wipe |
| `dryrun.jsonl` | where batches go when the endpoint is configured empty |
| `state.json` | the last app version seen and the last flush attempt |
| `state.json` | the last app version seen, the last flush attempt, and the UTC day this state was first created. The date never leaves the device: only the `install_age` bucket is sent |
| `install_id.json` | the random install id and when it was minted |
| `disabled` | the tombstone; present means nothing is appended or sent |
@@ -162,10 +162,14 @@ most once per flush point and never grows a queue.
## Event schema
`SCHEMA_VERSION = 4`. `notice_version = 6` identifies the disclosed default-on
policy; it does not assert human consent or that a notice was seen. Schema 4
adds the `model_usage` and `tool_usage` events and the `ci` session source.
Schema-3 batches with `notice_version = 5` are still accepted without them, which
`SCHEMA_VERSION = 6`. `notice_version = 8` identifies the disclosed default-on
policy; it does not assert human consent or that a notice was seen. Schema 6
adds, to `model_usage`, the request count, reasoning tokens, whole seconds spent
waiting on the model and a four-bucket input-size histogram; adds a coarse
install age and three exec start labels to `session_start`; and adds the
`unclean` exit class. Schema 4 added the `model_usage` and `tool_usage` events
and the `ci` session source. Schema-4 and schema-3 batches are still accepted
without the schema-6 fields. Schema-3 batches with `notice_version = 5` are still accepted without them, which
is what the web and desktop control-plane relay sends. The closed
v2 contract still accepts only `consent_version = 4`, retaining its original
explicit opt-in meaning. Fields cannot be mixed between versions. The unchanged
@@ -178,8 +182,8 @@ new fields, surfaces, and `product_usage` events.
```jsonc
{
"schema_version": 4,
"notice_version": 6,
"schema_version": 6,
"notice_version": 8,
"sent_at": "2026-08-03T18:04:11Z", // RFC3339 UTC, second precision
"install_id": "3f2a…", // uuid v4, rotates every 90 days
"app_version": "0.9.12",
@@ -196,7 +200,7 @@ new fields, surfaces, and `product_usage` events.
| Field | Type | Source anchor | Rule |
|---|---|---|---|
| `schema_version` | `u32` | const in `crates/telemetry/src/event.rs` | Bumped on any field add/remove/retype. Never reused. Pinned by a golden snapshot test. |
| `notice_version` | `u32` | policy constant in `crates/telemetry/src/event.rs` | Exactly `6` for schema 4; identifies the disclosed opt-out policy, not a human acceptance record. |
| `notice_version` | `u32` | policy constant in `crates/telemetry/src/event.rs` | Exactly `8` for schema 6; identifies the disclosed opt-out policy, not a human acceptance record. |
| `sent_at` | RFC3339 | `chrono::Utc::now()` | Second precision. Per-**batch** only — events carry no timestamps at all. |
| `install_id` | uuid v4 | `crates/telemetry/src/envelope.rs` | Random, never derived, rotated every 90 days. See "Where it lives" above. |
| `app_version` | string | `env!("CARGO_PKG_VERSION")`, as at `crates/telemetry/src/lib.rs:112` | Must match `^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$`. |
@@ -284,14 +288,27 @@ Emitted once when `state.json`'s `last_version` differs from `app_version`.
### Event: `session_start`
```jsonc
{ "event": "session_start", "source": "interactive" }
{ "event": "session_start", "source": "interactive", "install_age": "older" }
```
`source` is `SessionSource` (`crates/state/src/lib.rs:34-41`) stringified by `session_source_to_str` (`:1909-1917`): `interactive | resume | fork | api | unknown | ci`.
`source` is `SessionSource` (`crates/telemetry/src/event.rs`), a closed enum declared in the telemetry crate: `interactive | resume | fork | api | unknown | ci | fleet_worker | agent | scripted`.
`ci` replaces the others whenever `CI` or `GITHUB_ACTIONS` is set to a true
value, including the Codewhale GitHub Action, so automated runs are never
counted as people. Only that boolean environment fact is read.
`fleet_worker`, `agent` and `scripted` separate automated `exec` sessions from
people. `fleet_worker` is an `exec` that Codewhale's own fleet dispatcher
started, `agent` is an `exec` started from inside an agent's shell command (only
the presence of a Codewhale-owned environment variable is read, never its
value), and `scripted` is an `exec` whose standard input or output is not a
terminal. When more than one applies the order is `fleet_worker`, `agent`, `ci`,
`scripted`. Other surfaces are unchanged.
`install_age` is `new_today | under_week | older | null`: a coarse bucket of how
long this installation has existed. It is computed on your device and only the
bucket leaves it; the date it comes from is stored only in the local state file
and never leaves the device. The same UTC day is `new_today`, 1 to 6 days is `under_week`, and 7 or more is `older`. An installation whose state predates this field reports `older`, never `new_today`. `null` means the local state could not be read.
### Event: `session_end`
The workhorse. Everything a session accumulated ships here, once.
@@ -317,11 +334,11 @@ The workhorse. Everything a session accumulated ships here, once.
**`duration_bucket`** — `chrono` delta from `app.session_started_at` (`crates/tui/src/tui/app.rs:1889`). Half-open, seconds: `lt_1m` (`d < 60`), `1m_10m` (`60 ≤ d < 600`), `10m_60m` (`600 ≤ d < 3600`), `gt_60m` (`d ≥ 3600`).
**`exit_class`** — `clean | signal | panic | error`. **Derived from an explicit `AtomicU8`, never from an exit code.** `RunTerminationReason::Canceled` maps to exit 130 (`crates/engine/src/core/runtime_contract/termination.rs:53`), the same value the signal task uses (`crates/tui/src/lib.rs:682`, 128+SIGINT), so a code-based derivation would report every Esc-cancelled turn as a signal. The atomic is set by the panic hook (`crates/tui/src/lib.rs:1582`), by the signal task (`:678-696`) before `std::process::exit`, and on the clean path from `RunTerminationReason::is_success()` (`crates/engine/src/core/runtime_contract/termination.rs:44-46`) — `error` otherwise. Exit codes remain insufficient: an approval-required exit (3) and a terminal exec failure (1) need their actual termination classification.
**`exit_class`** — `clean | signal | panic | error | unclean`. `unclean` means the process ended without its own shutdown report and its totals were recovered from a local checkpoint at a later start. **Derived from an explicit `AtomicU8`, never from an exit code.** `RunTerminationReason::Canceled` maps to exit 130 (`crates/engine/src/core/runtime_contract/termination.rs:53`), the same value the signal task uses (`crates/tui/src/lib.rs:682`, 128+SIGINT), so a code-based derivation would report every Esc-cancelled turn as a signal. The atomic is set by the panic hook (`crates/tui/src/lib.rs:1582`), by the signal task (`:678-696`) before `std::process::exit`, and on the clean path from `RunTerminationReason::is_success()` (`crates/engine/src/core/runtime_contract/termination.rs:44-46`) — `error` otherwise. Exit codes remain insufficient: an approval-required exit (3) and a terminal exec failure (1) need their actual termination classification.
**`cold_start_bucket`** — from `startup_trace::elapsed_ms()`, which reads `PROCESS_START` directly and is independent of the startup summary's buffer clear (`crates/runtime/src/startup_trace.rs:39-45`). Boundaries: `lt_250`, `250_1000`, `1000_3000`, `gte_3000`. Absent on non-TUI surfaces.
**`providers`** — sorted, deduplicated array of `ProviderKind::as_str()` (`crates/config/src/provider_kind.rs:295`, a `&'static str` from a closed enum; `Custom` yields the literal `"custom"`). **The API takes `ProviderKind` by value, never `&str`.** Do not call `ProviderKind::parse` or `parse_config_identity` (`:300`, `:330`) — those are for config-table resolution. **Do not read** `provider_identity_for_persistence()` (`crates/tui/src/tui/app.rs:5049`), `provider_id_for_persistence()` (`:5058`), `ExecStreamMeta.provider_id` (`crates/app-server/src/exec_agent.rs`), or `PlannedTurnRoute.effective_provider_label` (`crates/engine/src/turn_route_plan.rs:189-193`) — all four return the customer's own `[providers.<name>]` table key when the route is Custom. This is the single most likely leak in the feature: it is one field away from the natural seam and `/status` already prints it (`crates/tui/src/commands/groups/config/status.rs:24-28`). **No model id is ever sent, for any provider** — `crates/runtime/src/safe_label.rs:11-15` documents that a model id can be a path, a URL, or a deployment id that is itself a credential.
**`providers`** — sorted, deduplicated array of `ProviderKind::as_str()` (`crates/config/src/provider_kind.rs:295`, a `&'static str` from a closed enum; `Custom` yields the literal `"custom"`). **The API takes `ProviderKind` by value, never `&str`.** Do not call `ProviderKind::parse` or `parse_config_identity` (`:300`, `:330`) — those are for config-table resolution. **Do not read** `provider_identity_for_persistence()` (`crates/tui/src/tui/app.rs:5049`), `provider_id_for_persistence()` (`:5058`), `ExecStreamMeta.provider_id` (`crates/app-server/src/exec_agent.rs`), or `PlannedTurnRoute.effective_provider_label` (`crates/engine/src/turn_route_plan.rs:189-193`) — all four return the customer's own `[providers.<name>]` table key when the route is Custom. This is the single most likely leak in the feature: it is one field away from the natural seam and `/status` already prints it (`crates/tui/src/commands/groups/config/status.rs:24-28`). **No model id outside the bundled public catalog is ever sent, for any provider** — `crates/runtime/src/safe_label.rs:11-15` documents that a model id can be a path, a URL, or a deployment id that is itself a credential. Those are sent as `other`; see `model_usage`.
**`counters`** — closed field set. Every bump happens at the **call site**, never inside a conditionally-entered handler:
@@ -443,9 +460,13 @@ to make defaults, and whether prompt caching is working.
"input_tokens": 418230,
"output_tokens": 9120,
"cache_read_tokens": 380001,
"cache_write_tokens": 0
"cache_write_tokens": 0,
"requests": 27,
"reasoning_tokens": 2310,
"generation_secs": 412
},
"turn_wall": { "lt_5s": 3, "5_30s": 8, "30_120s": 2, "gte_120s": 0 }
"turn_wall": { "lt_5s": 3, "5_30s": 8, "30_120s": 2, "gte_120s": 0 },
"context": { "lt_32k": 9, "32k_128k": 11, "128k_256k": 5, "gte_256k": 2 }
}
```
@@ -458,6 +479,25 @@ cache reads. Turn counts are by outcome, and `turn_wall` buckets each turn's
wall time as `session_end` does. A session reports at most 16 provider and model
pairs; later pairs are counted under `other`. No per-turn timeline is sent.
Schema 6 adds four aggregates to each row:
- `requests` counts the model requests this session made on its own route for
that provider and model.
- `reasoning_tokens` is the part of `output_tokens` the provider reports as
reasoning. `output_tokens` is not reduced, and the value is `0` when the
provider does not report it.
- `generation_secs` is the total whole seconds the session spent waiting on the
model for those requests. It is one sum for the session; no per-request
duration is ever sent.
- `context` counts requests by input size, in tokens including cache reads:
`lt_32k` is under 32768, `32k_128k` is 32768 up to 131072, `128k_256k` is
131072 up to 262144, and `gte_256k` is 262144 or more. The four buckets add up
to `requests`. Each edge belongs to the higher bucket. No per-request size is
sent.
Until a client fills them these values are `0`. A schema-4 row carries none of
these fields.
### Event: `tool_usage`
One event per tool a session called, sent with `session_end`. It is how
@@ -508,7 +548,7 @@ configured ingest may forward validated schema-v3 / notice-v5 batches and
legacy schema-v2 / consent-v4 batches to
PostHog's [batch capture API](https://posthog.com/docs/api/capture). The only
permitted origins are `https://us.i.posthog.com` and `https://eu.i.posthog.com`.
Schema-v1 and schema-v4 batches cannot reach that path in this source. PostHog receives the same bounded
Schema-v1, schema-v4 and schema-v6 batches cannot reach that path in this source. PostHog receives the same bounded
envelope and event fields, the batch timestamp as its event timestamp, and
`codewhale:<install_id>` as its anonymous `distinct_id`. Events are named
`codewhale_install_or_upgrade`, `codewhale_session_start`,
@@ -558,7 +598,7 @@ It prints the daily series, a 7-day trend over complete UTC days, the freshness
### What is never collected — the public red-line list
Prompts; completions; tool arguments; diffs; patches; file contents; filenames; absolute or relative paths; git remotes; repo names; branch names; workspace commit SHAs; memory entries; chat history; API keys, tokens, cookies, or `Authorization` headers (including any boolean asserting a key exists); model ids that are not in Codewhale's bundled public model catalog (custom, local, fine-tuned or private model names are sent only as `other`); custom provider table names; MCP server names, commands, URLs, or tool names; plugin and configured tool names; approval rule text; error message bodies; panic message text; per-event timestamps; keystrokes; clipboard; screenshots; microphone; camera; location; and any third-party ad or analytics SDK — there are none in the runtime binary and none may be added.
Prompts; completions; tool arguments; diffs; patches; file contents; filenames; absolute or relative paths; git remotes; repo names; branch names; workspace commit SHAs; memory entries; chat history; API keys, tokens, cookies, or `Authorization` headers (including any boolean asserting a key exists); model ids that are not in Codewhale's bundled public model catalog (custom, local, fine-tuned or private model names are sent only as `other`); custom provider table names; MCP server names, commands, URLs, or tool names; plugin and configured tool names; approval rule text; error message bodies; panic message text; per-event timestamps; per-request durations or sizes; environment variable values; CI vendor or job names; parent process names; hostnames; container ids; the date an installation was first seen (only the install-age bucket leaves the device); keystrokes; clipboard; screenshots; microphone; camera; location; and any third-party ad or analytics SDK — there are none in the runtime binary and none may be added.
Two named traps for the implementer. `crates/state/src/lib.rs` persists `git_sha`, `git_branch`, `git_origin_url`, `cwd`, and `path` on the threads table (`:93, :399, :653`): a payload builder that accepts a `Thread` or `ThreadMeta` and derives `Serialize` breaches the contract in one line. **Never derive `Serialize` over an existing state type** — build every telemetry struct from scratch with explicit fields. And `crates/core/src/lib.rs:1389-1398` is the one place in the tree where the word `telemetry` sits inside a JSON object next to `prompt`, `base_url`, and `has_api_key`. It is the object someone will copy. Do not.
@@ -567,7 +607,7 @@ Two named traps for the implementer. `crates/state/src/lib.rs` persists `git_sha
## Website funnel aggregates in the source candidate
The website extension uses `FUNNEL_SCHEMA_VERSION = 5` and notice version `7`.
The Rust runtime remains on `SCHEMA_VERSION = 4`, notice `6`; existing browser
The Rust runtime is on `SCHEMA_VERSION = 6`, notice `8`; existing browser
schema `3`, notice `5`, and legacy schemas `1` and `2` retain their original
contracts. Displaying a newer notice never overrides an opt-out or establishes
human acceptance. Schema 5 is first-party only and does not activate PostHog.
+3 -3
View File
@@ -2,8 +2,8 @@
"_comment": "Ceiling for dead-code suppressions across crates/, counting both `#[allow(dead_code)]` and `#[expect(dead_code)]`. `total` is the sum and is the ratcheted figure. It may go down freely; raising it needs a reviewer to say why in the PR. Regenerate with: python3 scripts/check-dead-code-budget.py --update",
"_issue": "https://github.com/codewhale-hq/CodeWhale/issues/4785",
"_expect_blind_spot": "Until #6241 this gate counted only the `allow` spelling, so rewriting an allow as an expect lowered the number without removing any dead code. The ceiling was re-based to the true combined count when that was fixed; it is not a regression.",
"total": 116,
"allow_total": 84,
"total": 121,
"allow_total": 89,
"expect_total": 32,
"per_crate": {
"app-server": {
@@ -55,7 +55,7 @@
"expect": 0
},
"tui": {
"allow": 31,
"allow": 36,
"expect": 20
}
}
+8 -7
View File
@@ -15,9 +15,9 @@ hostname is the only way in.
The current Engine source defaults usage analytics on under notice version 6, with a
clear opt-out. Prior explicit declines remain off; a missing acceptance record
is not treated as consent. Schema 4 carries `notice_version: 6`; schema 3
is not treated as consent. Schema 6 carries `notice_version: 8` and schema 4 carries `notice_version: 6`; schema 3
uses notice 5, and legacy schema 2 retains its original explicit
`consent_version: 4` contract. Schema 1 and schema 4 batches are first-party
`consent_version: 4` contract. Schema 1, 4 and 6 batches are first-party
only in this source. Local validation is not proof this updated Worker has been deployed. A user who wants
to contact nobody sets `telemetry_endpoint = ""`, which writes batches to
`$CODEWHALE_HOME/telemetry/dryrun.jsonl` instead.
@@ -38,7 +38,7 @@ require separate operator approval; none is established by the local tests.
Validated schema 3 batches carrying `notice_version: 5` and legacy schema 2
batches carrying explicit `consent_version: 4` can reach the processor. Schema 1
and schema 4 batches remain first-party only. Capture uses
and schema 4 and 6 batches remain first-party only. Capture uses
`/batch/`, fixed anonymous/no-geo controls, no incoming headers, no cookies,
no redirects, no response parsing, no retries, and a 1.5-second timeout.
PostHog failure is isolated from the successful Analytics Engine write.
@@ -143,20 +143,21 @@ take the next free slot.
| `blob8` | `tty` — `'true'` \| `'false'` |
| `blob9` | `install_kind` (`install_or_upgrade` only) |
| `blob10` | `previous_version` (`install_or_upgrade` only) |
| `blob11` | `session_source` (`session_start` only) |
| `blob12` | `duration_bucket` (`session_end` only) |
| `blob13` | `exit_class` (`session_end` only) |
| `blob11` | `session_source` (`session_start` only; schema 6 adds `fleet_worker`, `agent`, `scripted`) |
| `blob12` | `duration_bucket` (`session_end`); `install_age` (`session_start`, schema 6 only: `new_today`, `under_week`, `older`, `''` for null or older schemas) |
| `blob13` | `exit_class` (`session_end` only; schema 6 adds `unclean`) |
| `blob14` | `cold_start_bucket` (`session_end` only; `''` on surfaces that do not measure it) |
| `blob15` | `providers`, comma-joined, already sorted and deduplicated; the one `provider` on `model_usage` |
| `blob16` | `panic_site` (`panic`) — a `crates/…` path or the literal `<dep>`; `model` (`model_usage`); `tool` (`tool_usage`) |
| `blob17` | `sent_at` — the *batch* timestamp. Events carry none. |
| `blob18` | `aggregate_counters` — closed JSON counts, for `product_usage` or `operations_summary` |
| `blob19` | `schema_version` |
| `blob20` | `privacy_version`: notice6 for v4, notice5 for v3, consent4 for v2, empty for v1; `blob19` keeps their meanings distinct |
| `blob20` | `privacy_version`: notice8 for v6, notice7 for the v5 website funnel, notice6 for v4, notice5 for v3, consent4 for v2, empty for v1; `blob19` keeps their meanings distinct |
| `double1..10` | `counters`: `turns`, `tool_calls`, `fleet_dispatch`, `workflow_run`, `subagent_spawn`, `mcp_server_connected`, `memory_search`, `approval_modal_shown`, `approval_auto_allowed`, `command_palette_open` |
| `double11..16` | `errors`: `auth_preflight_failed`, `provider_http_4xx`, `provider_http_5xx`, `tool_denied_by_policy`, `tool_timeout`, `network_error` |
| `double17..20` | `turn_wall`: `lt_5s`, `5_30s`, `30_120s`, `gte_120s` |
| `double1..11` on `model_usage` | `turns_ok`, `turns_failed`, `turns_interrupted`, `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`, then `turn_wall` `lt_5s`, `5_30s`, `30_120s`, `gte_120s` |
| `double12..18` on `model_usage` | schema 6 only, `0` on v4 rows (`blob19` tells them apart): `requests`, `reasoning_tokens`, `generation_secs` (whole seconds, session sum, u32), then input-size request counts `lt_32k`, `32k_128k`, `128k_256k`, `gte_256k` |
| `double1..2` on `tool_usage` | `calls`, `errors` |
Columns not relevant to an event are `''` / `0`. `tty` is a blob because the 20
+5 -5
View File
@@ -13,7 +13,7 @@ export const CAVEATS = [
"Runtime install means first initialized enabled telemetry state, not all installations or new people. IDs rotate every 90 days and are removed on opt-out.",
"Native success is observed model turns_ok, not a first-ever primary or useful task. Missing usage, same-process child activity and late cancellation can affect it.",
"Dates are received batch dates rather than exact event times. Offline, opted-out and dropped deliveries are absent; ingest has no replay deduplication guarantee.",
"Native IDs with an observed CI start are excluded in full because the aggregate schema cannot assign model counts to individual sessions.",
"Native IDs with an observed CI, fleet worker, agent or scripted start are excluded in full because the aggregate schema cannot assign model counts to individual sessions.",
];
function instant(value, field) {
@@ -72,7 +72,7 @@ export function buildFunnelReport(input, { now = new Date() } = {}) {
const installs = new Map(); const successes = new Map(); const started = new Set(); const ci = new Set();
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
for (const row of input.native_rows) {
if (!uuid.test(row.install_id) || !NATIVE_SURFACES.includes(row.surface) || ![1, 2, 3, 4].includes(count(row.schema_version, "schema_version"))) throw new Error("invalid native identity, surface or version");
if (!uuid.test(row.install_id) || !NATIVE_SURFACES.includes(row.surface) || ![1, 2, 3, 4, 6].includes(count(row.schema_version, "schema_version"))) throw new Error("invalid native identity, surface or version");
const at = instant(fresh(row.received_at), "received_at");
if (!within(at, from, to)) throw new Error("native row outside coverage");
if (newest === null || at > newest) newest = at;
@@ -82,11 +82,11 @@ export function buildFunnelReport(input, { now = new Date() } = {}) {
if (!["install", "upgrade", "downgrade"].includes(row.install_kind)) throw new Error("invalid install kind");
if (row.install_kind === "install" && (!installs.has(row.install_id) || at < installs.get(row.install_id))) installs.set(row.install_id, at);
} else if (row.event === "session_start") {
if (!["interactive", "resume", "fork", "api", "unknown", "ci"].includes(row.session_source)) throw new Error("invalid session source");
if (row.session_source === "ci") ci.add(row.install_id);
if (!["interactive", "resume", "fork", "api", "unknown", "ci", "fleet_worker", "agent", "scripted"].includes(row.session_source)) throw new Error("invalid session source");
if (["ci", "fleet_worker", "agent", "scripted"].includes(row.session_source)) ci.add(row.install_id);
started.add(row.install_id);
} else if (row.event === "model_usage") {
if (count(row.schema_version, "schema_version") !== 4) throw new Error("model usage requires v4");
if (![4, 6].includes(count(row.schema_version, "schema_version"))) throw new Error("model usage requires v4 or v6");
if (count(row.turns_ok, "turns_ok") > 0) {
const observations = successes.get(row.install_id) ?? []; observations.push(at); successes.set(row.install_id, observations);
}
+14 -4
View File
@@ -24,7 +24,14 @@
*/
import type { Batch, Event } from "./schema";
import { COUNTER_FIELDS, ERROR_FIELDS, MODEL_COUNTER_FIELDS, TURN_WALL_FIELDS } from "./schema";
import {
CONTEXT_FIELDS,
COUNTER_FIELDS,
ERROR_FIELDS,
MODEL_COUNTER_FIELDS,
MODEL_COUNTER_FIELDS_V6_EXTRA,
TURN_WALL_FIELDS,
} from "./schema";
/** The subset of `AnalyticsEngineDataset` this Worker uses. */
export interface DataPointSink {
@@ -58,7 +65,7 @@ export const BLOB_COLUMNS = [
"install_kind", // blob9
"previous_version", // blob10
"session_source", // blob11
"duration_bucket", // blob12
"duration_bucket", // blob12 session_end; install_age on session_start (schema 6)
"exit_class", // blob13
"cold_start_bucket", // blob14
"providers", // blob15 comma-joined, already sorted and deduplicated
@@ -66,7 +73,7 @@ export const BLOB_COLUMNS = [
"sent_at", // blob17 the batch timestamp; events carry none
"aggregate_counters", // blob18 closed product/operations JSON count object
"schema_version", // blob19
"privacy_version", // blob20: v3/v4 notice, v2 consent, empty on v1; blob19 disambiguates
"privacy_version", // blob20: v3 to v6 notice, v2 consent, empty on v1; blob19 disambiguates
] as const;
/**
@@ -111,6 +118,7 @@ function toDataPoint(batch: Batch, event: Event): DataPoint {
break;
case "session_start":
blobs[10] = event.source;
blobs[11] = event.install_age ?? "";
break;
case "session_end":
blobs[11] = event.duration_bucket;
@@ -141,8 +149,10 @@ function toDataPoint(batch: Batch, event: Event): DataPoint {
doubles = [
...MODEL_COUNTER_FIELDS.map((field) => event.counters[field]),
...TURN_WALL_FIELDS.map((field) => event.turn_wall[field]),
...EMPTY_DOUBLES.slice(MODEL_COUNTER_FIELDS.length + TURN_WALL_FIELDS.length),
...MODEL_COUNTER_FIELDS_V6_EXTRA.map((field) => event.counters[field] ?? 0),
...CONTEXT_FIELDS.map((field) => event.context?.[field] ?? 0),
];
doubles = [...doubles, ...EMPTY_DOUBLES.slice(doubles.length)];
break;
case "tool_usage":
blobs[15] = event.tool;
+77 -21
View File
@@ -22,6 +22,8 @@ export const SCHEMA_VERSION = 4;
/** Notice-v5 batches without `model_usage`, `tool_usage` or the `ci` source. */
export const V3_SCHEMA_VERSION = 3;
export const V6_SCHEMA_VERSION = 6;
export const FUNNEL_SCHEMA_VERSION = 5;
export const FUNNEL_NOTICE_VERSION = 7;
export const FUNNEL_COUNTER_FIELDS = [
@@ -34,6 +36,8 @@ export const FUNNEL_COUNTER_FIELDS = [
/** Disclosed default-on policy, not a record of human acceptance. */
export const NOTICE_VERSION = 6;
export const V6_NOTICE_VERSION = 8;
/** The notice version schema v3 batches carry. */
export const V3_NOTICE_VERSION = 5;
@@ -146,6 +150,11 @@ export const SESSION_SOURCES = [
"ci",
] as const;
export const V6_ONLY_SESSION_SOURCES = ["fleet_worker", "agent", "scripted"] as const;
export const V6_SESSION_SOURCES = [...SESSION_SOURCES, ...V6_ONLY_SESSION_SOURCES] as const;
export const INSTALL_AGES = ["new_today", "under_week", "older"] as const;
/** `DurationBucket` wire spellings. */
export const DURATION_BUCKETS = [
"lt_1m",
@@ -157,6 +166,8 @@ export const DURATION_BUCKETS = [
/** `ExitClass::as_str`. */
export const EXIT_CLASSES = ["clean", "signal", "panic", "error"] as const;
export const V6_EXIT_CLASSES = [...EXIT_CLASSES, "unclean"] as const;
/** `ColdStartBucket` wire spellings. */
export const COLD_START_BUCKETS = [
"lt_250",
@@ -211,6 +222,19 @@ export const MODEL_COUNTER_FIELDS = [
"cache_write_tokens",
] as const;
export const MODEL_COUNTER_FIELDS_V6_EXTRA = [
"requests",
"reasoning_tokens",
"generation_secs",
] as const;
export const V6_MODEL_COUNTER_FIELDS = [
...MODEL_COUNTER_FIELDS,
...MODEL_COUNTER_FIELDS_V6_EXTRA,
] as const;
export const CONTEXT_FIELDS = ["lt_32k", "32k_128k", "128k_256k", "gte_256k"] as const;
/** `event::TOOL_NAMES` plus the `mcp` and `other` buckets. */
export const TOOL_NAMES = [
"agent", "apply_patch", "authenticate", "bash", "code_execution", "create_goal",
@@ -286,6 +310,12 @@ export const EVENT_FIELDS: Readonly<Record<string, readonly string[]>> = {
funnel_usage: ["event", "counters"],
};
export const V6_EVENT_FIELDS: Readonly<Record<string, readonly string[]>> = {
...EVENT_FIELDS,
session_start: ["event", "source", "install_age"],
model_usage: ["event", "provider", "model", "counters", "turn_wall", "context"],
};
/** Every event discriminant, for the doc-match test. */
export const EVENT_NAMES = Object.keys(EVENT_FIELDS);
@@ -430,7 +460,7 @@ export type FunnelCounters = Record<(typeof FUNNEL_COUNTER_FIELDS)[number], numb
export type Event =
| { event: "install_or_upgrade"; kind: string; previous_version: string | null }
| { event: "session_start"; source: string }
| { event: "session_start"; source: string; install_age?: string | null }
| {
event: "session_end";
duration_bucket: string;
@@ -448,8 +478,10 @@ export type Event =
event: "model_usage";
provider: string;
model: string;
counters: Record<(typeof MODEL_COUNTER_FIELDS)[number], number>;
counters: Record<(typeof MODEL_COUNTER_FIELDS)[number], number> &
Partial<Record<(typeof MODEL_COUNTER_FIELDS_V6_EXTRA)[number], number>>;
turn_wall: TurnWall;
context?: Record<(typeof CONTEXT_FIELDS)[number], number>;
}
| { event: "tool_usage"; tool: string; calls: number; errors: number }
| ({ event: "operations_summary" } & Record<(typeof OPERATIONS_FIELDS)[number], number>);
@@ -546,13 +578,28 @@ function u32Map(
return null;
}
function validateEvent(value: unknown, where: string): string | null {
function u32Fields(
value: Record<string, unknown>,
fields: readonly string[],
where: string,
): string | null {
for (const field of fields) {
const item = value[field];
if (typeof item !== "number" || !Number.isInteger(item) || item < 0 || item > U32_MAX) {
return `${where}.${field}: not a u32`;
}
}
return null;
}
function validateEvent(value: unknown, where: string, v6 = false): string | null {
if (!isPlainObject(value)) return `${where}: not an object`;
const name = value.event;
if (typeof name !== "string" || !Object.hasOwn(EVENT_FIELDS, name)) {
const eventFields = v6 ? V6_EVENT_FIELDS : EVENT_FIELDS;
if (typeof name !== "string" || !Object.hasOwn(eventFields, name)) {
return `${where}: unknown event discriminant`;
}
const keyError = keysExactly(value, EVENT_FIELDS[name], `${where}(${name})`);
const keyError = keysExactly(value, eventFields[name], `${where}(${name})`);
if (keyError) return keyError;
switch (name) {
@@ -575,8 +622,15 @@ function validateEvent(value: unknown, where: string): string | null {
}
return null;
}
case "session_start":
return enumString(value.source, SESSION_SOURCES, `${where}.source`);
case "session_start": {
const sourceError = enumString(
value.source,
v6 ? V6_SESSION_SOURCES : SESSION_SOURCES,
`${where}.source`,
);
if (sourceError || !v6 || value.install_age === null) return sourceError;
return enumString(value.install_age, INSTALL_AGES, `${where}.install_age`);
}
case "session_end": {
const bucketError = enumString(
value.duration_bucket,
@@ -586,7 +640,7 @@ function validateEvent(value: unknown, where: string): string | null {
if (bucketError) return bucketError;
const exitError = enumString(
value.exit_class,
EXIT_CLASSES,
v6 ? V6_EXIT_CLASSES : EXIT_CLASSES,
`${where}.exit_class`,
);
if (exitError) return exitError;
@@ -638,9 +692,14 @@ function validateEvent(value: unknown, where: string): string | null {
if (typeof value.model !== "string" || !MODEL_RE.test(value.model)) {
return `${where}.model: not a catalogued model id`;
}
const counterError = v6
? countMap(value.counters, V6_MODEL_COUNTER_FIELDS, `${where}.counters`, Number.MAX_SAFE_INTEGER) ??
u32Fields(value.counters as Record<string, unknown>, ["requests", "generation_secs"], `${where}.counters`)
: countMap(value.counters, MODEL_COUNTER_FIELDS, `${where}.counters`, Number.MAX_SAFE_INTEGER);
return (
countMap(value.counters, MODEL_COUNTER_FIELDS, `${where}.counters`, Number.MAX_SAFE_INTEGER) ??
u32Map(value.turn_wall, TURN_WALL_FIELDS, `${where}.turn_wall`)
counterError ??
u32Map(value.turn_wall, TURN_WALL_FIELDS, `${where}.turn_wall`) ??
(v6 ? u32Map(value.context, CONTEXT_FIELDS, `${where}.context`) : null)
);
}
case "tool_usage":
@@ -675,15 +734,12 @@ export function validateBatch(value: unknown): Accepted | Rejection {
const legacy = value.schema_version === 1;
const explicitConsent = value.schema_version === 2;
const v3 = value.schema_version === V3_SCHEMA_VERSION;
const v4 = value.schema_version === SCHEMA_VERSION;
const funnel = value.schema_version === FUNNEL_SCHEMA_VERSION;
const preUsage = value.schema_version !== SCHEMA_VERSION && !funnel;
if (
!legacy &&
!explicitConsent &&
value.schema_version !== SCHEMA_VERSION &&
!funnel &&
value.schema_version !== V3_SCHEMA_VERSION
) {
const v6 = value.schema_version === V6_SCHEMA_VERSION;
const preUsage = legacy || explicitConsent || v3;
if (!legacy && !explicitConsent && !v3 && !v4 && !funnel && !v6) {
return { ok: false, reason: "batch.schema_version: unsupported" };
}
const fields = legacy ? LEGACY_ENVELOPE_FIELDS : explicitConsent ? V2_ENVELOPE_FIELDS : ENVELOPE_FIELDS;
@@ -695,7 +751,7 @@ export function validateBatch(value: unknown): Accepted | Rejection {
if (
!legacy &&
!explicitConsent &&
value.notice_version !== (funnel ? FUNNEL_NOTICE_VERSION : preUsage ? V3_NOTICE_VERSION : NOTICE_VERSION)
value.notice_version !== (funnel ? FUNNEL_NOTICE_VERSION : v6 ? V6_NOTICE_VERSION : preUsage ? V3_NOTICE_VERSION : NOTICE_VERSION)
) {
return { ok: false, reason: "batch.notice_version: current policy required" };
}
@@ -753,7 +809,7 @@ export function validateBatch(value: unknown): Accepted | Rejection {
return { ok: false, reason: "events: aggregate product/operations events require schema v2 or v3" };
}
if (preUsage && (event.event === "model_usage" || event.event === "tool_usage")) {
return { ok: false, reason: "events: model_usage and tool_usage require schema v4" };
return { ok: false, reason: "events: model_usage and tool_usage require schema v4 or later" };
}
if (preUsage && event.event === "session_start" && event.source === "ci") {
return { ok: false, reason: "events: the ci session source requires schema v4" };
@@ -762,7 +818,7 @@ export function validateBatch(value: unknown): Accepted | Rejection {
return { ok: false, reason: "events: operations_summary requires control-plane surface" };
}
}
const eventError = validateEvent(event, `events[${index}]`);
const eventError = validateEvent(event, `events[${index}]`, v6);
if (eventError) return { ok: false, reason: eventError };
}
+3 -3
View File
@@ -97,12 +97,12 @@ describe("additive website funnel contract", () => {
}
});
it("keeps all four historical goldens accepted and runtime v4 first-party only", async () => {
it("keeps the historical goldens and v6 accepted, with runtime v4 and v6 first-party only", async () => {
const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);
for (const version of [1, 2, 3, 4]) {
for (const version of [1, 2, 3, 4, 6]) {
const batch = JSON.parse(readFileSync(new URL(`../../crates/telemetry/tests/golden/v${version}.json`, import.meta.url), "utf8"));
expect(validateBatch(batch).ok, `v${version}`).toBe(true);
if (version !== 4) continue;
if (version !== 4 && version !== 6) continue;
const { env, written } = harness();
expect((await worker.fetch(postJson(batch), { ...env, POSTHOG_HOST: "https://us.i.posthog.com", POSTHOG_PROJECT_TOKEN: "phc_local_test_fixture", POSTHOG_IP_SAFE_EGRESS_VERIFIED: "true" })).status).toBe(204);
expect(written).toHaveLength(batch.events.length);
+147 -1
View File
@@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest";
import worker from "../src/index";
import { INGEST_PATH } from "../src/route";
import { BLOB_COLUMNS, DOUBLE_COLUMNS } from "../src/datapoint";
import { MAX_BODY_BYTES, SURFACES } from "../src/schema";
import { MAX_BODY_BYTES, SURFACES, validateBatch } from "../src/schema";
import { goldenBatch, harness, post, postJson } from "./support";
describe("method and route", () => {
@@ -473,3 +473,149 @@ describe("failing closed and quiet", () => {
}
});
});
describe("schema 6", () => {
const golden = (version: number): Record<string, any> =>
JSON.parse(
readFileSync(
new URL(`../../crates/telemetry/tests/golden/v${version}.json`, import.meta.url),
"utf8",
),
);
const event = (batch: Record<string, any>, name: string) =>
batch.events.find((item: Record<string, any>) => item.event === name);
it("accepts every historical golden and the v6 golden", () => {
for (const version of [1, 2, 3, 4, 6]) {
expect(validateBatch(golden(version)).ok, `v${version}`).toBe(true);
}
});
it("answers 204 to the v4 and v6 goldens", async () => {
for (const version of [4, 6]) {
const { env, written } = harness();
expect((await worker.fetch(postJson(golden(version)), env)).status).toBe(204);
expect(written).toHaveLength(golden(version).events.length);
}
});
it("requires notice 8 on v6 and refuses the v4 notice", () => {
const batch = golden(6);
batch.notice_version = 6;
expect(validateBatch(batch).ok).toBe(false);
expect(validateBatch({ ...golden(4), notice_version: 8 }).ok).toBe(false);
});
it("refuses a v4 batch carrying any v6 key or value", () => {
const mutations: Array<(batch: Record<string, any>) => void> = [
(batch) => { event(batch, "model_usage").context = event(golden(6), "model_usage").context; },
(batch) => { event(batch, "model_usage").counters.requests = 1; },
(batch) => { event(batch, "model_usage").counters.reasoning_tokens = 1; },
(batch) => { event(batch, "model_usage").counters.generation_secs = 1; },
(batch) => { event(batch, "session_start").install_age = "older"; },
(batch) => { event(batch, "session_start").source = "fleet_worker"; },
(batch) => { event(batch, "session_start").source = "agent"; },
(batch) => { event(batch, "session_start").source = "scripted"; },
(batch) => { event(batch, "session_end").exit_class = "unclean"; },
];
for (const [index, mutate] of mutations.entries()) {
const batch = golden(4);
mutate(batch);
expect(validateBatch(batch).ok, `mutation ${index}`).toBe(false);
}
});
it("refuses a v6 batch missing or adding a key", () => {
const mutations: Array<(batch: Record<string, any>) => void> = [
(batch) => { delete event(batch, "model_usage").context; },
(batch) => { delete event(batch, "model_usage").context["32k_128k"]; },
(batch) => { event(batch, "model_usage").context.gte_512k = 0; },
(batch) => { delete event(batch, "model_usage").counters.requests; },
(batch) => { delete event(batch, "model_usage").counters.reasoning_tokens; },
(batch) => { delete event(batch, "model_usage").counters.generation_secs; },
(batch) => { event(batch, "model_usage").counters.generation_ms = 1; },
(batch) => { event(batch, "model_usage").model_family = "x"; },
(batch) => { delete event(batch, "session_start").install_age; },
(batch) => { event(batch, "session_start").extra = "x"; },
(batch) => { event(batch, "session_end").counters.requests = 1; },
];
for (const [index, mutate] of mutations.entries()) {
const batch = golden(6);
mutate(batch);
expect(validateBatch(batch).ok, `mutation ${index}`).toBe(false);
}
});
it("refuses open values where v6 has a closed set or a count", () => {
const mutations: Array<(batch: Record<string, any>) => void> = [
(batch) => { event(batch, "session_start").install_age = "2026-11-01"; },
(batch) => { event(batch, "session_start").install_age = "OLDER"; },
(batch) => { event(batch, "session_start").source = "github-actions"; },
(batch) => { event(batch, "session_end").exit_class = "killed"; },
(batch) => { event(batch, "model_usage").counters.requests = 4294967296; },
(batch) => { event(batch, "model_usage").counters.requests = 1.5; },
(batch) => { event(batch, "model_usage").counters.generation_secs = -1; },
(batch) => { event(batch, "model_usage").counters.generation_secs = 4294967296; },
(batch) => { event(batch, "model_usage").counters.generation_secs = 1794528251123; },
(batch) => { event(batch, "model_usage").counters.reasoning_tokens = "7"; },
(batch) => { event(batch, "model_usage").context.lt_32k = 4294967296; },
(batch) => { event(batch, "model_usage").context.lt_32k = "1"; },
(batch) => { event(batch, "model_usage").model = "/Users/someone/model"; },
];
for (const [index, mutate] of mutations.entries()) {
const batch = golden(6);
mutate(batch);
expect(validateBatch(batch).ok, `mutation ${index}`).toBe(false);
}
});
it("accepts a null install_age and every v6 source and exit class", () => {
for (const source of ["interactive", "resume", "fork", "api", "unknown", "ci", "fleet_worker", "agent", "scripted"]) {
for (const age of ["new_today", "under_week", "older", null]) {
const batch = golden(6);
event(batch, "session_start").source = source;
event(batch, "session_start").install_age = age;
expect(validateBatch(batch).ok, `${source}/${age}`).toBe(true);
}
}
for (const exit of ["clean", "signal", "panic", "error", "unclean"]) {
const batch = golden(6);
event(batch, "session_end").exit_class = exit;
expect(validateBatch(batch).ok, exit).toBe(true);
}
});
it("writes v6 model_usage after the unchanged eleven doubles, and leaves v4 rows zero there", async () => {
const v6 = harness();
await worker.fetch(postJson(golden(6)), v6.env);
const row = v6.written.find((point) => point.blobs[0] === "model_usage")!;
expect(row.doubles).toEqual([
12, 1, 0, 418230, 9120, 380001, 0,
3, 8, 2, 0,
27, 2310, 412,
9, 11, 5, 2,
0, 0,
]);
expect(row.blobs[BLOB_COLUMNS.indexOf("schema_version")]).toBe("6");
const v4 = harness();
await worker.fetch(postJson(golden(4)), v4.env);
const old = v4.written.find((point) => point.blobs[0] === "model_usage")!;
expect(old.doubles).toEqual([
12, 1, 0, 418230, 9120, 380001, 0,
3, 8, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
]);
});
it("writes install_age to blob12 of session_start rows only", async () => {
const { env, written } = harness();
await worker.fetch(postJson(golden(6)), env);
const start = written.find((point) => point.blobs[0] === "session_start")!;
expect(start.blobs[BLOB_COLUMNS.indexOf("session_source")]).toBe("fleet_worker");
expect(start.blobs[BLOB_COLUMNS.indexOf("duration_bucket")]).toBe("under_week");
const end = written.find((point) => point.blobs[0] === "session_end")!;
expect(end.blobs[BLOB_COLUMNS.indexOf("exit_class")]).toBe("unclean");
expect(end.blobs[BLOB_COLUMNS.indexOf("duration_bucket")]).toBe("1m_10m");
});
});
@@ -49,6 +49,19 @@ describe("existing-pipeline owner funnel report", () => {
expect(buildFunnelReport(input, { now: NOW }).native.seven_day_initialization_cohort.unavailable_reason).toContain("incomplete");
});
it("excludes fleet worker, agent and scripted starts like CI, and accepts v6 model usage", () => {
for (const source of ["fleet_worker", "agent", "scripted"]) {
const input = receipt();
input.native_rows.push({ ...native("session_start", "2026-10-04T00:00:00Z"), session_source: source });
input.native_rows.push({ ...native("model_usage", "2026-10-04T00:00:00Z"), schema_version: 6 });
const report = buildFunnelReport(input, { now: NOW });
expect(report.native.excluded_ci_ids, source).toBe(1);
expect(report.native.observed_completed_ids, source).toBe(0);
}
const input = receipt(); input.native_rows.push({ ...native("model_usage", "2026-10-04T00:00:00Z"), schema_version: 5 });
expect(() => buildFunnelReport(input, { now: NOW })).toThrow(/version/);
});
it("does not compute a cohort fraction from sampled native records", () => {
const input = receipt(); input.native_rows[0].weight = 4;
expect(buildFunnelReport(input, { now: NOW }).native.seven_day_initialization_cohort).toMatchObject({ fraction: null, sampled: true });
+21 -4
View File
@@ -20,23 +20,27 @@ import {
BATCH_MAX_BYTES,
BATCH_MAX_EVENTS,
COLD_START_BUCKETS,
CONTEXT_FIELDS,
COUNTER_FIELDS,
DURATION_BUCKETS,
ENVELOPE_FIELDS,
ERROR_FIELDS,
EVENT_FIELDS,
EVENT_NAMES,
EXIT_CLASSES,
INSTALL_AGES,
INSTALL_KINDS,
LIBCS,
MAX_BODY_BYTES,
OSES,
PRODUCT_COUNTER_FIELDS,
OPERATIONS_FIELDS,
SCHEMA_VERSION,
SESSION_SOURCES,
SURFACES,
TURN_WALL_FIELDS,
V6_EVENT_FIELDS as EVENT_FIELDS,
V6_EXIT_CLASSES as EXIT_CLASSES,
V6_MODEL_COUNTER_FIELDS,
V6_NOTICE_VERSION,
V6_SCHEMA_VERSION as SCHEMA_VERSION,
V6_SESSION_SOURCES as SESSION_SOURCES,
} from "../src/schema";
import { DOC, goldenBatch } from "./support";
@@ -168,6 +172,16 @@ describe("the doc and the validator publish the same fields", () => {
expect([...documentedKeys(BLOCKS[3])].sort()).toEqual(expected);
});
it("agrees on the model_usage field set, nested objects included", () => {
const expected = [
...EVENT_FIELDS.model_usage,
...V6_MODEL_COUNTER_FIELDS,
...TURN_WALL_FIELDS,
...CONTEXT_FIELDS,
].sort();
expect([...documentedKeys(BLOCKS[7])].sort()).toEqual([...new Set(expected)].sort());
});
it("agrees on the panic field set", () => {
expect([...documentedKeys(BLOCKS[4])].sort()).toEqual(
[...EVENT_FIELDS.panic].sort(),
@@ -216,6 +230,7 @@ describe("the doc and the validator publish the same enums", () => {
["session source", SESSION_SOURCES],
["duration bucket", DURATION_BUCKETS],
["exit class", EXIT_CLASSES],
["install age", INSTALL_AGES],
["cold start bucket", COLD_START_BUCKETS],
] as const)("publishes every %s value it accepts", (_label, values) => {
for (const value of values) {
@@ -232,6 +247,8 @@ describe("the doc and the validator publish the same limits", () => {
expect(match).not.toBeNull();
expect(Number((match as RegExpMatchArray)[1])).toBe(SCHEMA_VERSION);
expect(goldenBatch().schema_version).toBe(1); // preserved legacy golden
const notice = DOC.match(/`notice_version\s*=\s*(\d+)`/);
expect(Number((notice as RegExpMatchArray)[1])).toBe(V6_NOTICE_VERSION);
});
it("agrees on the per-batch caps", () => {