diff --git a/lib/summary.js b/lib/summary.js index 65c90d180..52fc94f98 100644 --- a/lib/summary.js +++ b/lib/summary.js @@ -28,6 +28,8 @@ * 0: each model keeps its last measured value under that value's date, the * window names every such gap, and with nothing measured total.hf and the * huggingface component are null and left out of the sums (lib/huggingface.js). + * A first-party telemetry count under ten, zero included, is null in + * total.telemetry, never 0 (lib/telemetry-withheld.js). */ const fs = require('fs'); const path = require('path'); @@ -37,6 +39,7 @@ const { computeMomentum } = require('./momentum'); const { computeReach } = require('./reach'); const { computeCommunity } = require('./community'); const { huggingfaceDownloads } = require('./huggingface'); +const { floorCount, WITHHELD } = require('./telemetry-withheld'); const CRYPTO_REPO = 'ecolibria/cryptoserve'; @@ -47,6 +50,34 @@ function tableExists(db, name) { return !!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(name); } +/** + * total.telemetry: first-party CLI telemetry, ACTIVE USERS (distinct installs + * over rolling windows), from the Registry's coarse public adoption feed. Not + * a download count; excluded from every series. Latest snapshot only, or null + * when none is stored. A count under ten, zero included, is null (withheld), + * never 0; `withheld` states the rule beside the figures. + */ +function telemetrySummary(db) { + if (!tableExists(db, 'telemetry_snapshots')) return null; + const latest = db.prepare( + 'SELECT date, total_installs, wau, mau, engaged_mau, provenance FROM telemetry_snapshots ORDER BY date DESC LIMIT 1' + ).get(); + if (!latest) return null; + const toolCount = db.prepare('SELECT COUNT(*) as count FROM telemetry_tool_snapshots WHERE date = ?').get(latest.date); + const countryCount = db.prepare('SELECT COUNT(*) as count FROM telemetry_country_snapshots WHERE date = ?').get(latest.date); + return { + asOf: latest.date, + totalInstalls: floorCount(latest.total_installs), + wau: floorCount(latest.wau), + mau: floorCount(latest.mau), + engagedMau: floorCount(latest.engaged_mau), + withheld: { ...WITHHELD }, + tools: toolCount?.count || 0, + countries: countryCount?.count || 0, + provenance: latest.provenance || '', + }; +} + function dateRange(db, table) { if (!tableExists(db, table)) return { first: null, asOf: null }; const r = db.prepare(`SELECT MIN(date) AS first, MAX(date) AS asOf FROM ${table}`).get(); @@ -243,29 +274,7 @@ function buildSummary(db, { dataDir, env = process.env, now = new Date() } = {}) for (const e of exts) chromeUsers += latestUsers.get(e.id)?.users || 0; } - // First-party CLI telemetry — ACTIVE USERS (distinct installs over rolling - // windows), from the Registry's coarse public adoption feed. Not a download - // count; excluded from every series. Latest snapshot only. - let telemetry = null; - if (tableExists(db, 'telemetry_snapshots')) { - const latest = db.prepare( - 'SELECT date, total_installs, wau, mau, engaged_mau, provenance FROM telemetry_snapshots ORDER BY date DESC LIMIT 1' - ).get(); - if (latest) { - const toolCount = db.prepare('SELECT COUNT(*) as count FROM telemetry_tool_snapshots WHERE date = ?').get(latest.date); - const countryCount = db.prepare('SELECT COUNT(*) as count FROM telemetry_country_snapshots WHERE date = ?').get(latest.date); - telemetry = { - asOf: latest.date, - totalInstalls: latest.total_installs, - wau: latest.wau, - mau: latest.mau, - engagedMau: latest.engaged_mau ?? 0, - tools: toolCount?.count || 0, - countries: countryCount?.count || 0, - provenance: latest.provenance || '', - }; - } - } + const telemetry = telemetrySummary(db); const npmPkgCount = db.prepare('SELECT COUNT(*) as count FROM npm_packages').get(); @@ -388,4 +397,4 @@ function buildSummary(db, { dataDir, env = process.env, now = new Date() } = {}) }; } -module.exports = { buildSummary, COLLECTORS, seriesStatus }; +module.exports = { buildSummary, COLLECTORS, seriesStatus, telemetrySummary }; diff --git a/lib/telemetry-withheld.js b/lib/telemetry-withheld.js new file mode 100644 index 000000000..1d21740b2 --- /dev/null +++ b/lib/telemetry-withheld.js @@ -0,0 +1,89 @@ +/** + * The floor on first-party telemetry counts. + * + * A count under ten is withheld, zero included. It is stored and served as + * null, and a person reads WITHHELD_LABEL where the number would be. Zero + * takes the label too: if 0 were shown and only one to nine were withheld, + * the label would mean "at least one". + * + * The label is never a number. A withheld figure is never shown as 0, never + * sorted as if it held a value, and never added into a figure the page + * computes. + * + * Pure: no db, no network, no clock. Shared by the collector, the API route, + * the dashboard, the summary and the store cleaning step. + */ + +const WITHHELD_FLOOR = 10; +const WITHHELD_LABEL = 'fewer than 10'; +const WITHHELD_NOTE = 'Figures under ten are withheld, zero included.'; + +// Served beside the figures so a null reads as withheld, not as missing. +const WITHHELD = Object.freeze({ below: WITHHELD_FLOOR, label: WITHHELD_LABEL }); + +/** + * A count at or above the floor, or null. Null, a count from 0 to 9, and + * anything that is not a finite number all come out as null. + */ +function floorCount(v) { + if (typeof v !== 'number' || !Number.isFinite(v)) return null; + const n = Math.trunc(v); + return n >= WITHHELD_FLOOR ? n : null; +} + +/** The text a person reads for a count: the number, or the withheld label. */ +function formatTelemetryCount(v) { + const n = floorCount(v); + return n === null ? WITHHELD_LABEL : n.toLocaleString(); +} + +/** + * Comparator for rows ordered by a count, largest first. A row whose count is + * withheld follows every measured row, and withheld rows are ordered by `key` + * alone: their place says nothing about the count they hide. Ties on a + * measured count are ordered by `key` too. + */ +function byMeasuredDesc(field, key) { + const byKey = (a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0); + return (a, b) => { + const x = floorCount(a[field]); + const y = floorCount(b[field]); + if (x === null && y === null) return byKey(a, b); + if (x === null) return 1; + if (y === null) return -1; + return y - x || byKey(a, b); + }; +} + +/** + * The version with the most installs among those with a measured count, or + * null when every version's count is withheld. A withheld version is never + * named as the top one. + */ +function topMeasuredVersion(versions) { + let top = null; + for (const v of Array.isArray(versions) ? versions : []) { + const n = floorCount(v && v.installs); + if (n !== null && (top === null || n > top.installs)) top = { version: v.version, installs: n }; + } + return top; +} + +/** The provenance text with the withheld note added once. */ +function withWithheldNote(text) { + const base = typeof text === 'string' ? text.trim() : ''; + if (base.includes(WITHHELD_NOTE)) return base; + return base ? `${base} ${WITHHELD_NOTE}` : WITHHELD_NOTE; +} + +module.exports = { + WITHHELD, + WITHHELD_FLOOR, + WITHHELD_LABEL, + WITHHELD_NOTE, + byMeasuredDesc, + floorCount, + formatTelemetryCount, + topMeasuredVersion, + withWithheldNote, +}; diff --git a/lib/telemetry.js b/lib/telemetry.js index b230e1748..20246cce3 100644 --- a/lib/telemetry.js +++ b/lib/telemetry.js @@ -12,6 +12,8 @@ * a SQLite file. The collector and the API routes import it. */ +const { floorCount, WITHHELD_LABEL } = require('./telemetry-withheld'); + // Registry tool-id → dashboard product display name. Mirrors the product names // used in pages/api/overview.js productMap so the same tool reads consistently // across the download and active-user surfaces. Unknown ids fall through to the @@ -42,6 +44,20 @@ function toCount(v) { return Math.trunc(v); } +// One figure from the feed: a count, or null when the feed withholds it. +// Anything else (a missing key, a string, a negative or non-finite number) is +// not a figure and comes back as undefined so the caller can reject it. +function readFigure(v) { + if (v === null) return null; + const n = toCount(v); + return n === null ? undefined : n; +} + +// A figure older feeds may omit (engagedMau): absent reads as withheld. +function readOptionalFigure(v) { + return v === undefined ? null : readFigure(v); +} + /** * Validate + normalize the Registry public adoption feed into the shape the * collector persists. Throws on a structurally invalid payload — an empty field @@ -49,47 +65,65 @@ function toCount(v) { * with zeros. Every numeric field is measured by the Registry; we only coerce * types and drop rows we cannot trust. * + * Every count comes out floored (lib/telemetry-withheld.js): a figure the feed + * withholds (null) and any count from 0 to 9 are null, so nothing downstream + * (the store, the badge, the log line) holds a figure under ten. A tool row + * whose figures are withheld is kept; a row carrying a value that is not a + * figure is dropped as untrusted. + * * @param {object} feed parsed JSON from the public adoption endpoint * @returns {{generatedAt:string, retentionDays:number, wauWindowDays:number, - * mauWindowDays:number, totalInstalls:number, wau:number, mau:number, - * tools:Array, byCountry:Array}} + * mauWindowDays:number, totalInstalls:number|null, wau:number|null, + * mau:number|null, engagedMau:number|null, tools:Array, byCountry:Array}} */ function normalizeAdoptionFeed(feed) { if (!feed || typeof feed !== 'object') { throw new Error('adoption feed is not an object'); } - const totalInstalls = toCount(feed.totalInstalls); - const wau = toCount(feed.wau); - const mau = toCount(feed.mau); - if (totalInstalls === null || wau === null || mau === null) { + const totalInstalls = readFigure(feed.totalInstalls); + const wau = readFigure(feed.wau); + const mau = readFigure(feed.mau); + if (totalInstalls === undefined || wau === undefined || mau === undefined) { throw new Error('adoption feed missing/invalid fleet totals (totalInstalls/wau/mau)'); } + const engagedMau = readOptionalFigure(feed.engagedMau); + if (engagedMau === undefined) { + throw new Error('adoption feed has an invalid fleet engagedMau'); + } const tools = []; for (const t of Array.isArray(feed.tools) ? feed.tools : []) { if (!t || typeof t.tool !== 'string' || t.tool === '') continue; - const ti = toCount(t.totalInstalls); - const tw = toCount(t.wau); - const tm = toCount(t.mau); - if (ti === null || tw === null || tm === null) continue; // skip untrusted row, don't zero it - // engagedMau is the sybil-dampened floor; older feeds may omit it → default 0. - const teng = toCount(t.engagedMau) ?? 0; + const ti = readFigure(t.totalInstalls); + const tw = readFigure(t.wau); + const tm = readFigure(t.mau); + // engagedMau is the sybil-dampened floor; older feeds may omit it. + const teng = readOptionalFigure(t.engagedMau); + // skip untrusted row, don't zero it; a withheld (null) figure keeps its row + if (ti === undefined || tw === undefined || tm === undefined || teng === undefined) continue; const versions = []; for (const v of Array.isArray(t.versions) ? t.versions : []) { if (!v || typeof v.version !== 'string' || v.version === '') continue; - const vi = toCount(v.installs); - if (vi === null) continue; - versions.push({ version: v.version, installs: vi }); + const vi = readFigure(v.installs); + if (vi === undefined) continue; + versions.push({ version: v.version, installs: floorCount(vi) }); } - tools.push({ tool: t.tool, totalInstalls: ti, wau: tw, mau: tm, engagedMau: teng, versions }); + tools.push({ + tool: t.tool, + totalInstalls: floorCount(ti), + wau: floorCount(tw), + mau: floorCount(tm), + engagedMau: floorCount(teng), + versions, + }); } const byCountry = []; for (const c of Array.isArray(feed.byCountry) ? feed.byCountry : []) { if (!c || typeof c.countryCode !== 'string' || c.countryCode === '') continue; - const ci = toCount(c.installs); - if (ci === null) continue; - byCountry.push({ countryCode: c.countryCode, installs: ci }); + const ci = readFigure(c.installs); + if (ci === undefined) continue; + byCountry.push({ countryCode: c.countryCode, installs: floorCount(ci) }); } return { @@ -101,13 +135,13 @@ function normalizeAdoptionFeed(feed) { retentionDays: toCount(feed.retentionDays) ?? 0, wauWindowDays: toCount(feed.wauWindowDays) ?? 0, mauWindowDays: toCount(feed.mauWindowDays) ?? 0, - totalInstalls, - wau, - mau, + totalInstalls: floorCount(totalInstalls), + wau: floorCount(wau), + mau: floorCount(mau), // Sybil-dampened floor (installs with a real multi-day footprint). The - // honest, defensible headline; raw wau/mau are shown as context. Default 0 - // for older feeds that predate the field. - engagedMau: toCount(feed.engagedMau) ?? 0, + // honest, defensible headline; raw wau/mau are shown as context. Withheld + // (null), never 0, when under ten or absent from an older feed. + engagedMau: floorCount(engagedMau), engagedMinDays: toCount(feed.engagedMinDays) ?? 0, tools, byCountry, @@ -310,10 +344,12 @@ function classifyCollectionSkip({ * live snapshot means the alarm keeps ringing, and gets louder, until someone * fixes it or the fleet genuinely has no users to report. * - * This REPORTS but never suppresses the write: the zeros are what the feed said, - * and recording them honestly is right. Raising the alarm is the job. + * This REPORTS but never suppresses the write: the counts are what the feed said + * (floored, so a count under ten is stored as withheld), and recording them is + * right. Raising the alarm is the job. * - * @param {{mau:number, totalInstalls:number}} current normalized feed + * @param {{mau:number|null, totalInstalls:number|null}} current normalized feed; + * null is a withheld figure (under ten) and is named as such, never as 0 * @param {{mau:number, totalInstalls:number, date:string}|null} lastLive the * newest stored snapshot with mau > 0, or null if none exists (a brand-new * deployment, or a fleet that has genuinely never reported an active user — @@ -333,11 +369,16 @@ function classifyFeedHealth(current, lastLive, today) { const installs = Number(current.totalInstalls) || 0; const days = daysBetween(lastLive.date, today); const forHowLong = days === null || days < 0 ? '' : ` for ${days} day(s)`; + // The collector passes the floored feed, where a count under ten is null: + // it is named by the withheld label, never printed as 0. + const mauText = current.mau == null ? `mau ${WITHHELD_LABEL}` : `mau=${mau}`; // The install base still reporting while actives are zero is the tell: those // are different windows, and a real fleet cannot have installs but no actives. const installsClause = - installs > 0 + current.totalInstalls == null + ? `Installs are ${WITHHELD_LABEL} as well, so the retention window has nearly emptied too. ` + : installs > 0 ? `The feed still reports ${installs} install(s) over the retention window, which is exactly ` + 'what a drained ingest looks like: the 30-day active count empties first while the 90-day ' + 'install count is still coasting on old events. ' @@ -346,10 +387,10 @@ function classifyFeedHealth(current, lastLive, today) { return { level: 'error', message: sanitizeForLog( - `Telemetry feed reports mau=0${forHowLong}, but the last snapshot with any activity had ` + + `Telemetry feed reports ${mauText}${forHowLong}, but the last snapshot with any activity had ` + `mau=${lastMau} on ${lastLive.date}. ${installsClause}` + 'Users do not all disappear overnight — treat this as a broken ingest path until proven ' + - 'otherwise. The zeros were recorded as reported; investigate before trusting the dashboard.', + 'otherwise. The counts were recorded as reported; investigate before trusting the dashboard.', 500 ), }; diff --git a/pages/api/telemetry.js b/pages/api/telemetry.js index 08703e5ed..3912b405b 100644 --- a/pages/api/telemetry.js +++ b/pages/api/telemetry.js @@ -1,5 +1,6 @@ const Database = require('better-sqlite3'); const path = require('path'); +const { byMeasuredDesc, floorCount, WITHHELD } = require('../../lib/telemetry-withheld'); const { toolDisplayName } = require('../../lib/telemetry'); /** @@ -49,24 +50,30 @@ export default async function handler(req, res) { const versionRows = db.prepare( 'SELECT tool, version, installs FROM telemetry_version_snapshots WHERE date = ? ORDER BY tool, installs DESC, version' ).all(latest.date); + // Only floored counts are served: a count under ten, zero included, is + // null (withheld) and keeps its row, never 0 and never dropped. Rows are + // ordered on the floored count, so a withheld one follows every measured + // one, by name, and its place says nothing about the count it hides. const versionsByTool = {}; for (const v of versionRows) { - (versionsByTool[v.tool] ||= []).push({ version: v.version, installs: v.installs }); + (versionsByTool[v.tool] ||= []).push({ version: v.version, installs: floorCount(v.installs) }); } + for (const list of Object.values(versionsByTool)) list.sort(byMeasuredDesc('installs', 'version')); const tools = toolRows.map(t => ({ tool: t.tool, product: toolDisplayName(t.tool), - totalInstalls: t.total_installs, - wau: t.wau, - mau: t.mau, - engagedMau: t.engaged_mau ?? 0, + totalInstalls: floorCount(t.total_installs), + wau: floorCount(t.wau), + mau: floorCount(t.mau), + engagedMau: floorCount(t.engaged_mau), versions: versionsByTool[t.tool] || [], - })); + })).sort(byMeasuredDesc('mau', 'tool')); const byCountry = db.prepare( 'SELECT country_code, installs FROM telemetry_country_snapshots WHERE date = ? ORDER BY installs DESC, country_code' - ).all(latest.date).map(c => ({ countryCode: c.country_code, installs: c.installs })); + ).all(latest.date).map(c => ({ countryCode: c.country_code, installs: floorCount(c.installs) })) + .sort(byMeasuredDesc('installs', 'countryCode')); return res.status(200).json({ available: true, @@ -77,10 +84,10 @@ export default async function handler(req, res) { retentionDays: latest.retention_days, wauWindowDays: latest.wau_window_days, mauWindowDays: latest.mau_window_days, - totalInstalls: latest.total_installs, - wau: latest.wau, - mau: latest.mau, - engagedMau: latest.engaged_mau ?? 0, + totalInstalls: floorCount(latest.total_installs), + wau: floorCount(latest.wau), + mau: floorCount(latest.mau), + engagedMau: floorCount(latest.engaged_mau), engagedMinDays: latest.engaged_min_days ?? 0, wauGrowth7d: prior7 ? latest.wau - prior7.wau : 0, mauGrowth30d: prior30 ? latest.mau - prior30.mau : 0, @@ -88,6 +95,7 @@ export default async function handler(req, res) { }, tools, byCountry, + withheld: WITHHELD, }); } catch (err) { return res.status(500).json({ error: 'telemetry read failed' }); diff --git a/pages/index.js b/pages/index.js index a85cbffb4..42d2c5719 100644 --- a/pages/index.js +++ b/pages/index.js @@ -17,6 +17,9 @@ import { periodPick, hfPeriod, rowAdoption } from '../lib/adoption'; // as not measured and left out of totals, never as 0. import { sumMeasured, formatMeasured, measuredTooltipPayload, channelMixSubtitle, NOT_MEASURED } from '../lib/huggingface'; import { SERIES } from '../lib/series'; +// A first-party telemetry count under ten, zero included, is withheld: the API +// serves it as null and it reads "fewer than 10" here, never 0. +import { floorCount, formatTelemetryCount, topMeasuredVersion, withWithheldNote, WITHHELD_LABEL } from '../lib/telemetry-withheld'; /* ============================================================ Source identity — one place defines color + icon per source @@ -578,12 +581,7 @@ function OverviewTab({ overview, loading, trends, granularity, setGranularity, p {totals.chrome?.extensions > 0 && ( } color={C.chrome} label="Chrome Users" value={fmtFull(totals.chrome?.users || 0)} sub={`weekly active · ${totals.chrome?.extensions} ext`} /> )} - {tel?.snapshot && ( - } color={C.green} label="Active CLI Users" - value={fmtFull(tel.snapshot.engagedMau)} - sub={`engaged monthly · ${fmtFull(tel.snapshot.mau)} reported`} - delta={tel.snapshot.engagedGrowth30d ? pctChange(tel.snapshot.engagedMau, tel.snapshot.engagedMau - tel.snapshot.engagedGrowth30d) : null} /> - )} + {tel?.snapshot && } {WITHHELD_LABEL} : n.toLocaleString(); +} +/* Change against the earlier snapshot, or null. A withheld figure takes no + part in it: no percentage is computed from a withheld cell. */ +function telemetryDelta(current, growth) { + const curr = floorCount(current); + if (curr === null || !growth) return null; + return pctChange(curr, floorCount(curr - growth)); +} +/* The version with the most installs among those measured. When every + version's count is withheld, none is named as the top one. */ +function TopVersion({ versions }) { + const list = versions || []; + const top = topMeasuredVersion(list); + if (top) return {top.version} · {top.installs.toLocaleString()}; + if (list.length > 0) return each version {WITHHELD_LABEL}; + return —; +} +function ActiveCliUsersKpi({ snapshot: s }) { + return ( + } color={C.green} label="Active CLI Users" + value={} + sub={`engaged monthly · ${formatTelemetryCount(s.mau)} reported`} + delta={telemetryDelta(s.engagedMau, s.engagedGrowth30d)} /> + ); +} + function TelemetrySection({ data }) { const s = data.snapshot; const tools = data.tools || []; @@ -737,9 +766,9 @@ function TelemetrySection({ data }) { title="Active users, measured first-party" sub={`Distinct installs of the CLIs, reported by the tools themselves — active users, not downloads (a download is not a user), so they are shown separately and never summed into adoption. "Engaged" is the honest headline: installs active on ≥${s.engagedMinDays || 2} distinct days with real usage — a sybil-dampened floor that a burst of fabricated installs can't inflate. "Reported" WAU/MAU come from anonymous, unauthenticated telemetry and are best-effort/forgeable. As of ${s.asOf}.`}>
- } color={C.green} label="Engaged monthly users" value={fmtFull(s.engagedMau)} sub={`≥${s.engagedMinDays || 2}-day footprint · sybil-dampened floor`} delta={s.engagedGrowth30d ? pctChange(s.engagedMau, s.engagedMau - s.engagedGrowth30d) : null} /> - } color={C.accent} label="Reported MAU" value={fmtFull(s.mau)} sub={`${s.mauWindowDays || 30}-day distinct · best-effort`} delta={s.mauGrowth30d ? pctChange(s.mau, s.mau - s.mauGrowth30d) : null} /> - } color={C.npm} label="Reported WAU" value={fmtFull(s.wau)} sub={`${s.wauWindowDays || 7}-day distinct · best-effort`} delta={s.wauGrowth7d ? pctChange(s.wau, s.wau - s.wauGrowth7d) : null} /> + } color={C.green} label="Engaged monthly users" value={} sub={`≥${s.engagedMinDays || 2}-day footprint · sybil-dampened floor`} delta={telemetryDelta(s.engagedMau, s.engagedGrowth30d)} /> + } color={C.accent} label="Reported MAU" value={} sub={`${s.mauWindowDays || 30}-day distinct · best-effort`} delta={telemetryDelta(s.mau, s.mauGrowth30d)} /> + } color={C.npm} label="Reported WAU" value={} sub={`${s.wauWindowDays || 7}-day distinct · best-effort`} delta={telemetryDelta(s.wau, s.wauGrowth7d)} />
{tools.length > 0 && ( @@ -749,11 +778,11 @@ function TelemetrySection({ data }) { {tools.map(t => (
{t.product}
{t.product !== t.tool &&
{t.tool}
} - {fmtFull(t.totalInstalls)} - {fmtFull(t.engagedMau)} - {fmtFull(t.mau)} - {fmtFull(t.wau)} - {t.versions?.[0] ? {t.versions[0].version} · {fmtFull(t.versions[0].installs)} : —} + + + + + ))} @@ -764,16 +793,17 @@ function TelemetrySection({ data }) {
{byCountry.slice(0, 12).map(c => ( - {c.countryCode} · {fmtFull(c.installs)} + {c.countryCode} · ))}
)} {/* Honest provenance, carried from the feed — these are self-reported over - anonymous telemetry, a best-effort signal, not a sybil-verified count. */} + anonymous telemetry, a best-effort signal, not a sybil-verified count. + The withheld note says once what "fewer than 10" means. */}
- {s.provenance || 'Self-reported by the CLIs over anonymous telemetry — a best-effort adoption signal, not a sybil-verified count.'} + {withWithheldNote(s.provenance || 'Self-reported by the CLIs over anonymous telemetry — a best-effort adoption signal, not a sybil-verified count.')}
diff --git a/scripts/collect-telemetry-stats.js b/scripts/collect-telemetry-stats.js index cc4ae6204..82bc4a1c1 100644 --- a/scripts/collect-telemetry-stats.js +++ b/scripts/collect-telemetry-stats.js @@ -4,6 +4,8 @@ const { URL } = require('url'); const Database = require('better-sqlite3'); const path = require('path'); const fs = require('fs'); +const { formatTelemetryCount } = require('../lib/telemetry-withheld'); +const { cleanTelemetryStore } = require('./floor-telemetry-counts'); require('dotenv').config(); @@ -274,11 +276,12 @@ function persist(db, feed) { function writeBadge(feed) { // Headline is monthly active users (the honest "how many people use this" - // number), mirroring the docker/hf badge convention. + // number), mirroring the docker/hf badge convention. A withheld MAU (under + // ten) reads "fewer than 10", never a number. const badge = { schemaVersion: 1, label: 'active CLI users (MAU)', - message: feed.mau.toLocaleString(), + message: formatTelemetryCount(feed.mau), color: 'brightgreen', style: 'flat', }; @@ -312,15 +315,21 @@ async function main() { const db = new Database(dbPath); try { + // The feed is floored by normalizeAdoptionFeed. The store step makes the + // count columns nullable before a withheld (NULL) count is written, and + // floors any count under ten an earlier run stored. + cleanTelemetryStore(db); persist(db, feed); writeBadge(feed); } finally { db.close(); } + // Floored figures only: this line lands in a public workflow log. console.log( - ' Installs: %d | WAU: %d | MAU: %d | engaged(MAU): %d | tools: %d | countries: %d', - feed.totalInstalls, feed.wau, feed.mau, feed.engagedMau, feed.tools.length, feed.byCountry.length + ' Installs: %s | WAU: %s | MAU: %s | engaged(MAU): %s | tools: %d | countries: %d', + formatTelemetryCount(feed.totalInstalls), formatTelemetryCount(feed.wau), formatTelemetryCount(feed.mau), + formatTelemetryCount(feed.engagedMau), feed.tools.length, feed.byCountry.length ); // A retrieval check cannot see a feed that answers 200 with drained numbers, diff --git a/scripts/floor-telemetry-counts.js b/scripts/floor-telemetry-counts.js new file mode 100644 index 000000000..4ce827d79 --- /dev/null +++ b/scripts/floor-telemetry-counts.js @@ -0,0 +1,287 @@ +/** + * Floor the stored first-party telemetry counts. + * + * Every count from 0 to 9 in the telemetry_*_snapshots tables is withheld: + * stored as NULL, never as a number and never as the column's old DEFAULT 0. + * Zero is included, because a series that shows 0 on some days and withheld on + * others reveals one to nine. Counts of 10 or more are kept as they are, and so + * is every row. + * + * The step is idempotent and safe to re-run on any copy of the store: + * 1. a table whose count columns still carry NOT NULL or a default is rebuilt + * with nullable counts, keeping every row; + * 2. every stored count under ten is set to NULL; + * 3. when 1 or 2 changed anything, the file is rebuilt (VACUUM), so no + * replaced value is left behind in free pages; secure_delete zeroes freed + * content during the run itself; + * 4. from the command line, the telemetry block of data/summary.json is + * rewritten from the floored store with the code generate-summary uses. + * + * setup-database.js and the collector run steps 1 to 3 on every collection, so + * the committed store stays floored. Usage: + * + * node scripts/floor-telemetry-counts.js [--db=data/analytics.db] [--summary=data/summary.json|none] + * + * It prints row counts only, never a stored figure, and exits 1 when a count + * under ten is still stored afterwards. + */ +const fs = require('fs'); +const path = require('path'); +const { WITHHELD_FLOOR } = require('../lib/telemetry-withheld'); + +// Every count column, per table. Window lengths and thresholds (retention_days, +// engaged_min_days, ...) are settings, not counts of installs, and are kept. +const TELEMETRY_COUNT_COLUMNS = Object.freeze({ + telemetry_snapshots: Object.freeze(['total_installs', 'wau', 'mau', 'engaged_mau']), + telemetry_tool_snapshots: Object.freeze(['total_installs', 'wau', 'mau', 'engaged_mau']), + telemetry_version_snapshots: Object.freeze(['installs']), + telemetry_country_snapshots: Object.freeze(['installs']), +}); + +// Count columns are nullable with no default: NULL is a withheld count (under +// ten, zero included), and an insert that leaves a count out stores NULL, not 0. +const TABLE_DDL = { + telemetry_snapshots: (name) => ` + CREATE TABLE IF NOT EXISTS ${name} ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + date TEXT NOT NULL, -- collection day (UTC) + generated_at TEXT, -- feed's measured-at timestamp (RFC3339) + provenance TEXT, -- honest basis + limits, carried from the feed (best-effort, not sybil-verified) + retention_days INTEGER NOT NULL DEFAULT 0, -- events retention backing the counts + wau_window_days INTEGER NOT NULL DEFAULT 0, + mau_window_days INTEGER NOT NULL DEFAULT 0, + total_installs INTEGER, -- fleet-wide distinct installs (retention window); NULL = withheld + wau INTEGER, -- fleet-wide weekly active installs; NULL = withheld + mau INTEGER, -- fleet-wide monthly active installs; NULL = withheld + engaged_mau INTEGER, -- sybil-dampened floor (>=2 active days + a command), <= mau; NULL = withheld + engaged_min_days INTEGER NOT NULL DEFAULT 0, -- active-days threshold behind engaged_mau + collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(date) + );`, + telemetry_tool_snapshots: (name) => ` + CREATE TABLE IF NOT EXISTS ${name} ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + date TEXT NOT NULL, + tool TEXT NOT NULL, -- Registry tool id (e.g. "hackmyagent") + total_installs INTEGER, -- NULL = withheld + wau INTEGER, -- NULL = withheld + mau INTEGER, -- NULL = withheld + engaged_mau INTEGER, -- sybil-dampened floor for this tool, <= mau; NULL = withheld + collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(date, tool) + );`, + telemetry_version_snapshots: (name) => ` + CREATE TABLE IF NOT EXISTS ${name} ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + date TEXT NOT NULL, + tool TEXT NOT NULL, + version TEXT NOT NULL, + installs INTEGER, -- distinct installs active on this version (MAU window); NULL = withheld + collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(date, tool, version) + );`, + telemetry_country_snapshots: (name) => ` + CREATE TABLE IF NOT EXISTS ${name} ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + date TEXT NOT NULL, + country_code TEXT NOT NULL, + installs INTEGER, -- distinct installs by country (retention window); NULL = withheld + collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(date, country_code) + );`, +}; + +// The columns of each table above, in order, for the rebuild copy. +const TABLE_COLUMNS = Object.freeze({ + telemetry_snapshots: ['id', 'date', 'generated_at', 'provenance', 'retention_days', 'wau_window_days', + 'mau_window_days', 'total_installs', 'wau', 'mau', 'engaged_mau', 'engaged_min_days', 'collected_at'], + telemetry_tool_snapshots: ['id', 'date', 'tool', 'total_installs', 'wau', 'mau', 'engaged_mau', 'collected_at'], + telemetry_version_snapshots: ['id', 'date', 'tool', 'version', 'installs', 'collected_at'], + telemetry_country_snapshots: ['id', 'date', 'country_code', 'installs', 'collected_at'], +}); + +const TABLE_INDEXES = { + telemetry_snapshots: '', + telemetry_tool_snapshots: 'CREATE INDEX IF NOT EXISTS idx_telemetry_tool_date ON telemetry_tool_snapshots(date);', + telemetry_version_snapshots: 'CREATE INDEX IF NOT EXISTS idx_telemetry_version_date ON telemetry_version_snapshots(date);', + telemetry_country_snapshots: 'CREATE INDEX IF NOT EXISTS idx_telemetry_country_date ON telemetry_country_snapshots(date);', +}; + +const TABLES = Object.keys(TELEMETRY_COUNT_COLUMNS); + +/** The four telemetry tables and their indexes, for setup-database.js. */ +function telemetrySchemaDdl() { + return TABLES.map(t => TABLE_DDL[t](t)).join('\n') + '\n' + + TABLES.map(t => TABLE_INDEXES[t]).filter(Boolean).join('\n'); +} + +function tableExists(db, name) { + return !!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(name); +} + +function countColumnsAreNullable(db, table) { + const counts = TELEMETRY_COUNT_COLUMNS[table]; + return db.prepare(`PRAGMA table_info(${table})`).all() + .filter(c => counts.includes(c.name)) + .every(c => !c.notnull && c.dflt_value === null); +} + +// The count columns a table has (an older table may lack one). +function presentCountColumns(db, table) { + const existing = new Set(db.prepare(`PRAGMA table_info(${table})`).all().map(c => c.name)); + return TELEMETRY_COUNT_COLUMNS[table].filter(c => existing.has(c)); +} + +/** + * Rebuild each existing telemetry table whose count columns still carry NOT + * NULL or a default, keeping every row. SQLite cannot drop NOT NULL in place. + * Every table is checked before any is changed, and all are rebuilt in one + * transaction, so a refusal leaves the store as it was. Returns the names of + * the tables rebuilt. + */ +function migrateTelemetryCounts(db) { + const plan = []; + for (const table of TABLES) { + if (!tableExists(db, table) || countColumnsAreNullable(db, table)) continue; + const existing = db.prepare(`PRAGMA table_info(${table})`).all().map(c => c.name); + const unknown = existing.filter(c => !TABLE_COLUMNS[table].includes(c)); + if (unknown.length > 0) { + // Rebuilding would drop these columns; stop rather than lose data. + throw new Error(`${table} has columns the floored schema does not carry: ${unknown.join(', ')}`); + } + plan.push({ table, cols: TABLE_COLUMNS[table].filter(c => existing.includes(c)).join(', ') }); + } + if (plan.length === 0) return []; + db.transaction(() => { + for (const { table, cols } of plan) { + const temp = `${table}_floor_rebuild`; + db.exec(`DROP TABLE IF EXISTS ${temp}`); + db.exec(TABLE_DDL[table](temp)); + db.exec(`INSERT INTO ${temp} (${cols}) SELECT ${cols} FROM ${table}`); + db.exec(`DROP TABLE ${table}`); + db.exec(`ALTER TABLE ${temp} RENAME TO ${table}`); + if (TABLE_INDEXES[table]) db.exec(TABLE_INDEXES[table]); + } + })(); + return plan.map(p => p.table); +} + +/** + * Set every stored count under ten to NULL, in one transaction. Returns the + * number of rows changed per existing table. + */ +function floorStoredTelemetryCounts(db) { + const changed = {}; + db.transaction(() => { + for (const table of TABLES) { + if (!tableExists(db, table)) continue; + const cols = presentCountColumns(db, table); + if (cols.length === 0) { changed[table] = 0; continue; } + const set = cols.map(c => `${c} = CASE WHEN ${c} < ${WITHHELD_FLOOR} THEN NULL ELSE ${c} END`).join(', '); + const where = cols.map(c => `${c} < ${WITHHELD_FLOOR}`).join(' OR '); + changed[table] = db.prepare(`UPDATE ${table} SET ${set} WHERE ${where}`).run().changes; + } + })(); + return changed; +} + +/** + * Rows that still hold a count from 0 to 9, per table (0 for a missing table). + * Every value must be 0 once the floor has run. + */ +function countsUnderFloor(db) { + const out = {}; + for (const table of TABLES) { + const cols = tableExists(db, table) ? presentCountColumns(db, table) : []; + if (cols.length === 0) { out[table] = 0; continue; } + const where = cols.map(c => `${c} BETWEEN 0 AND ${WITHHELD_FLOOR - 1}`).join(' OR '); + out[table] = db.prepare(`SELECT count(*) AS n FROM ${table} WHERE ${where}`).get().n; + } + return out; +} + +/** + * Steps 1 to 3 on an open, writable connection (no transaction open). + * Returns { rebuilt: [table], floored: { table: rows }, vacuumed: boolean }. + */ +function cleanTelemetryStore(db) { + db.pragma('secure_delete = ON'); + const rebuilt = migrateTelemetryCounts(db); + const floored = floorStoredTelemetryCounts(db); + const changedRows = Object.values(floored).reduce((a, b) => a + b, 0); + const vacuumed = rebuilt.length > 0 || changedRows > 0; + if (vacuumed) db.exec('VACUUM'); + return { rebuilt, floored, vacuumed }; +} + +/** + * Rewrite the telemetry block of a summary file from the store, with the same + * code generate-summary uses. Every other key is left as it was. Returns + * 'rewritten', 'unchanged' or 'absent'. + */ +function rewriteSummaryTelemetry(db, summaryPath) { + if (!fs.existsSync(summaryPath)) return 'absent'; + const raw = fs.readFileSync(summaryPath, 'utf8'); + const summary = JSON.parse(raw); + if (!summary || typeof summary.total !== 'object' || summary.total === null) return 'absent'; + const { telemetrySummary } = require('../lib/summary'); + const next = { ...summary, total: { ...summary.total, telemetry: telemetrySummary(db) } }; + const out = JSON.stringify(next, null, 2) + (raw.endsWith('\n') ? '\n' : ''); + if (out === raw) return 'unchanged'; + fs.writeFileSync(summaryPath, out); + return 'rewritten'; +} + +function parseArgs(argv) { + const dataDir = path.join(__dirname, '..', 'data'); + const args = { db: path.join(dataDir, 'analytics.db'), summary: path.join(dataDir, 'summary.json') }; + for (const a of argv) { + const m = /^--(db|summary)=(.+)$/.exec(a); + if (!m) throw new Error(`unknown argument: ${a} (expected --db= or --summary=|none)`); + args[m[1]] = m[2]; + } + if (args.summary === 'none') args.summary = null; + return args; +} + +function main() { + const args = parseArgs(process.argv.slice(2)); + if (!fs.existsSync(args.db)) throw new Error(`no database at ${args.db}`); + const Database = require('better-sqlite3'); + const db = new Database(args.db); + try { + const { rebuilt, floored, vacuumed } = cleanTelemetryStore(db); + console.log('Telemetry store floor (counts under ten withheld, zero included): %s', args.db); + console.log(' schema: %s', rebuilt.length ? `rebuilt with nullable counts: ${rebuilt.join(', ')}` : 'counts already nullable'); + for (const [table, rows] of Object.entries(floored)) console.log(' %s: %d row(s) set to withheld', table, rows); + console.log(' file rebuilt (VACUUM): %s', vacuumed ? 'yes' : 'no, nothing changed'); + if (args.summary) console.log(' summary telemetry block: %s', rewriteSummaryTelemetry(db, args.summary)); + const left = countsUnderFloor(db); + for (const [table, rows] of Object.entries(left)) console.log(' check %s rows with a count from 0 to 9: %d', table, rows); + if (Object.values(left).some(n => n !== 0)) { + console.error(' a count under ten is still stored'); + process.exitCode = 1; + } + } finally { + db.close(); + } +} + +if (require.main === module) { + try { + main(); + } catch (err) { + console.error('Error: %s', err && err.message); + process.exit(1); + } +} + +module.exports = { + TELEMETRY_COUNT_COLUMNS, + cleanTelemetryStore, + countsUnderFloor, + floorStoredTelemetryCounts, + migrateTelemetryCounts, + rewriteSummaryTelemetry, + telemetrySchemaDdl, +}; diff --git a/scripts/setup-database.js b/scripts/setup-database.js index 86f9638e0..6a714b6b9 100644 --- a/scripts/setup-database.js +++ b/scripts/setup-database.js @@ -2,6 +2,7 @@ const Database = require('better-sqlite3'); const path = require('path'); const fs = require('fs'); const { huggingfaceStatsDdl, HF_STATS_INDEXES, migrateHuggingfaceStats } = require('../lib/huggingface'); +const { telemetrySchemaDdl, cleanTelemetryStore } = require('./floor-telemetry-counts'); // Ensure data directory exists const dataDir = path.join(__dirname, '..', 'data'); @@ -395,57 +396,10 @@ ${huggingfaceStatsDdl('huggingface_stats')} -- cohorts, error rates) is fetched live behind ANALYTICS_TRACKER_PASSWORD from the -- Registry's authenticated internal endpoint and is never persisted. -- Daily snapshots (one row per collection day), like Chrome and HuggingFace. - CREATE TABLE IF NOT EXISTS telemetry_snapshots ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - date TEXT NOT NULL, -- collection day (UTC) - generated_at TEXT, -- feed's measured-at timestamp (RFC3339) - provenance TEXT, -- honest basis + limits, carried from the feed (best-effort, not sybil-verified) - retention_days INTEGER NOT NULL DEFAULT 0, -- events retention backing the counts - wau_window_days INTEGER NOT NULL DEFAULT 0, - mau_window_days INTEGER NOT NULL DEFAULT 0, - total_installs INTEGER NOT NULL DEFAULT 0, -- fleet-wide distinct installs (retention window) - wau INTEGER NOT NULL DEFAULT 0, -- fleet-wide weekly active installs - mau INTEGER NOT NULL DEFAULT 0, -- fleet-wide monthly active installs - engaged_mau INTEGER NOT NULL DEFAULT 0, -- sybil-dampened floor (>=2 active days + a command); <= mau - engaged_min_days INTEGER NOT NULL DEFAULT 0, -- active-days threshold behind engaged_mau - collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, - UNIQUE(date) - ); - - CREATE TABLE IF NOT EXISTS telemetry_tool_snapshots ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - date TEXT NOT NULL, - tool TEXT NOT NULL, -- Registry tool id (e.g. "hackmyagent") - total_installs INTEGER NOT NULL DEFAULT 0, - wau INTEGER NOT NULL DEFAULT 0, - mau INTEGER NOT NULL DEFAULT 0, - engaged_mau INTEGER NOT NULL DEFAULT 0, -- sybil-dampened floor for this tool; <= mau - collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, - UNIQUE(date, tool) - ); - - CREATE TABLE IF NOT EXISTS telemetry_version_snapshots ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - date TEXT NOT NULL, - tool TEXT NOT NULL, - version TEXT NOT NULL, - installs INTEGER NOT NULL DEFAULT 0, -- distinct installs active on this version (MAU window) - collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, - UNIQUE(date, tool, version) - ); - - CREATE TABLE IF NOT EXISTS telemetry_country_snapshots ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - date TEXT NOT NULL, - country_code TEXT NOT NULL, - installs INTEGER NOT NULL DEFAULT 0, -- distinct installs by country (retention window) - collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, - UNIQUE(date, country_code) - ); - - CREATE INDEX IF NOT EXISTS idx_telemetry_tool_date ON telemetry_tool_snapshots(date); - CREATE INDEX IF NOT EXISTS idx_telemetry_version_date ON telemetry_version_snapshots(date); - CREATE INDEX IF NOT EXISTS idx_telemetry_country_date ON telemetry_country_snapshots(date); + -- Count columns are nullable: a count under ten, zero included, is stored as + -- NULL (withheld), never as 0. The tables are defined in + -- scripts/floor-telemetry-counts.js, which also brings an older store to them. +${telemetrySchemaDdl()} `); // --- Idempotent migrations for pre-existing databases --- @@ -472,8 +426,9 @@ if (telSnapExists) { console.log('Migration: added telemetry_snapshots.provenance'); } // engagedMau (sybil-dampened floor) was added after the table first shipped. + // Rows from before it have no engaged count: NULL, never a 0. if (!telCols.includes('engaged_mau')) { - db.exec('ALTER TABLE telemetry_snapshots ADD COLUMN engaged_mau INTEGER NOT NULL DEFAULT 0'); + db.exec('ALTER TABLE telemetry_snapshots ADD COLUMN engaged_mau INTEGER'); console.log('Migration: added telemetry_snapshots.engaged_mau'); } if (!telCols.includes('engaged_min_days')) { @@ -488,11 +443,23 @@ const telToolExists = db.prepare( if (telToolExists) { const cols = db.prepare('PRAGMA table_info(telemetry_tool_snapshots)').all().map(c => c.name); if (!cols.includes('engaged_mau')) { - db.exec('ALTER TABLE telemetry_tool_snapshots ADD COLUMN engaged_mau INTEGER NOT NULL DEFAULT 0'); + db.exec('ALTER TABLE telemetry_tool_snapshots ADD COLUMN engaged_mau INTEGER'); console.log('Migration: added telemetry_tool_snapshots.engaged_mau'); } } +// Telemetry counts are floored: a table whose counts are still NOT NULL is +// rebuilt with nullable counts, and every stored count under ten, zero +// included, is set to NULL (withheld). Idempotent; prints row counts only. +const telemetryFloor = cleanTelemetryStore(db); +if (telemetryFloor.rebuilt.length > 0) { + console.log('Migration: rebuilt %s with nullable counts', telemetryFloor.rebuilt.join(', ')); +} +const telemetryWithheldRows = Object.values(telemetryFloor.floored).reduce((a, b) => a + b, 0); +if (telemetryWithheldRows > 0) { + console.log('Telemetry floor: %d stored row(s) had a count under ten set to withheld', telemetryWithheldRows); +} + // huggingface_stats counts became nullable (an absent API count is NULL with // absent_reason, never a measured 0); an older table is rebuilt in place. if (migrateHuggingfaceStats(db)) { diff --git a/test/telemetry-collector.test.js b/test/telemetry-collector.test.js index 609eb7333..1d3b0f825 100644 --- a/test/telemetry-collector.test.js +++ b/test/telemetry-collector.test.js @@ -191,7 +191,9 @@ test('a drained feed (mau=0, installs still live) errors — the shape a broken const res = await run({ REGISTRY_URL: url }, dbFile); assert.equal(res.status, 1, `expected an outage exit; stdout:\n${res.stdout}`); assert.match(res.stdout, /::error::/); - assert.match(res.stdout, /mau=0/); + // The feed's 0 is floored: the log names it withheld, never prints it. + assert.match(res.stdout, /mau fewer than 10/); + assert.doesNotMatch(res.stdout, /mau=0/); assert.match(res.stdout, /333 install/); } ); diff --git a/test/telemetry-withheld.test.js b/test/telemetry-withheld.test.js new file mode 100644 index 000000000..84d3e7d91 --- /dev/null +++ b/test/telemetry-withheld.test.js @@ -0,0 +1,635 @@ +const { test } = require('node:test'); +const assert = require('node:assert'); +const Module = require('node:module'); +const { spawn } = require('node:child_process'); +const { createHash } = require('node:crypto'); +const http = require('node:http'); +const { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = require('node:fs'); +const { join } = require('node:path'); +const { tmpdir } = require('node:os'); +const Database = require('better-sqlite3'); + +/* + * A first-party telemetry count under ten, zero included, is withheld. + * + * Followed through every place a count is kept or shown: the collector stores + * it as NULL (never the column's old DEFAULT 0), the store step clears every + * count under ten already stored, /api/telemetry keeps the row and serves null, + * and the dashboard reads "fewer than 10" where the number would be: never 0, + * never by dropping the row, never sorted as if it held a value, and never + * taken into a figure the page computes. + * + * Every fixture is synthetic. data/analytics.db is only ever copied, never + * written. Every server listens on 127.0.0.1. + */ + +const ROOT = join(__dirname, '..'); +const LABEL = 'fewer than 10'; +const NOTE = 'Figures under ten are withheld, zero included.'; + +// The telemetry tables as the store had them before counts became nullable: +// every count NOT NULL DEFAULT 0. +const NOT_NULL_SCHEMA = ` + CREATE TABLE telemetry_snapshots ( + id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, generated_at TEXT, provenance TEXT, + retention_days INTEGER NOT NULL DEFAULT 0, wau_window_days INTEGER NOT NULL DEFAULT 0, + mau_window_days INTEGER NOT NULL DEFAULT 0, total_installs INTEGER NOT NULL DEFAULT 0, + wau INTEGER NOT NULL DEFAULT 0, mau INTEGER NOT NULL DEFAULT 0, + engaged_mau INTEGER NOT NULL DEFAULT 0, engaged_min_days INTEGER NOT NULL DEFAULT 0, + collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(date)); + CREATE TABLE telemetry_tool_snapshots ( + id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, tool TEXT NOT NULL, + total_installs INTEGER NOT NULL DEFAULT 0, wau INTEGER NOT NULL DEFAULT 0, + mau INTEGER NOT NULL DEFAULT 0, engaged_mau INTEGER NOT NULL DEFAULT 0, + collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(date, tool)); + CREATE INDEX idx_telemetry_tool_date ON telemetry_tool_snapshots(date); + CREATE TABLE telemetry_version_snapshots ( + id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, tool TEXT NOT NULL, + version TEXT NOT NULL, installs INTEGER NOT NULL DEFAULT 0, + collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(date, tool, version)); + CREATE INDEX idx_telemetry_version_date ON telemetry_version_snapshots(date); + CREATE TABLE telemetry_country_snapshots ( + id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, country_code TEXT NOT NULL, + installs INTEGER NOT NULL DEFAULT 0, + collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(date, country_code)); + CREATE INDEX idx_telemetry_country_date ON telemetry_country_snapshots(date); +`; + +// The same tables with nullable counts, as a floored store holds them. +const NULLABLE_SCHEMA = NOT_NULL_SCHEMA.replace( + /\b(total_installs|wau|mau|engaged_mau|installs) INTEGER NOT NULL DEFAULT 0/g, '$1 INTEGER' +); + +const COUNT_COLUMNS = { + telemetry_snapshots: ['total_installs', 'wau', 'mau', 'engaged_mau'], + telemetry_tool_snapshots: ['total_installs', 'wau', 'mau', 'engaged_mau'], + telemetry_version_snapshots: ['installs'], + telemetry_country_snapshots: ['installs'], +}; + +// Rows still holding a count from 0 to 9: per tool, per version and fleet. +// Each must be 0 once the store is floored (a withheld count is NULL, which +// no BETWEEN counts). +const UNDER_TEN_CHECKS = [ + 'SELECT count(*) FROM telemetry_tool_snapshots WHERE total_installs BETWEEN 0 AND 9 OR wau BETWEEN 0 AND 9 OR mau BETWEEN 0 AND 9 OR engaged_mau BETWEEN 0 AND 9', + 'SELECT count(*) FROM telemetry_version_snapshots WHERE installs BETWEEN 0 AND 9', + 'SELECT count(*) FROM telemetry_snapshots WHERE wau BETWEEN 0 AND 9 OR mau BETWEEN 0 AND 9 OR engaged_mau BETWEEN 0 AND 9', +]; + +function tmp(prefix) { + return mkdtempSync(join(tmpdir(), `telem-withheld-${prefix}-`)); +} + +function storeAt(file, schema, seed = () => {}) { + const db = new Database(file); + try { + db.exec(schema); + seed(db); + } finally { + db.close(); + } + return file; +} + +function readOnly(file, fn) { + const db = new Database(file, { readonly: true }); + try { + return fn(db); + } finally { + db.close(); + } +} + +const underTenCounts = (file) => readOnly(file, db => UNDER_TEN_CHECKS.map(sql => db.prepare(sql).pluck().get())); +const sha256 = (file) => createHash('sha256').update(readFileSync(file)).digest('hex'); + +function spawnNode(args, { env = {}, cwd }) { + return new Promise((resolve) => { + const child = spawn(process.execPath, args, { env: { ...process.env, ...env }, cwd }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (d) => (stdout += d)); + child.stderr.on('data', (d) => (stderr += d)); + child.on('close', (status) => resolve({ status, stdout, stderr })); + }); +} + +// The real collector against a stub feed on 127.0.0.1 and a scratch store. +// It runs in the store's directory, so the only .env it can load is none. +function collect(feed, dbFile) { + const server = http.createServer((req, res) => { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(feed)); + }); + return new Promise((resolve, reject) => { + server.listen(0, '127.0.0.1', async () => { + try { + const dir = join(dbFile, '..'); + resolve(await spawnNode([join(ROOT, 'scripts', 'collect-telemetry-stats.js')], { + cwd: dir, + env: { + REGISTRY_URL: `http://127.0.0.1:${server.address().port}`, + TELEMETRY_DB_PATH: dbFile, + TELEMETRY_BADGE_PATH: join(dir, 'telemetry-badge.json'), + TELEMETRY_FEED_TIMEOUT_MS: '5000', + GITHUB_ACTIONS: '', + }, + })); + } catch (e) { + reject(e); + } finally { + server.close(); + } + }); + }); +} + +function floorStore(dbFile, summary = 'none') { + return spawnNode([join(ROOT, 'scripts', 'floor-telemetry-counts.js'), `--db=${dbFile}`, `--summary=${summary}`], { + cwd: join(dbFile, '..'), + }); +} + +// /api/telemetry, loaded as Next.js serves it (its ES module default export +// rewritten to a CommonJS one), answering from /data/analytics.db. +async function serveTelemetry(dir) { + const file = join(ROOT, 'pages', 'api', 'telemetry.js'); + const source = readFileSync(file, 'utf8'); + const exportLine = 'export default async function handler('; + assert.ok(source.includes(exportLine), 'the route is a default-exported async function'); + const mod = new Module(file); + mod.filename = file; + mod.paths = Module._nodeModulePaths(join(ROOT, 'pages', 'api')); + mod._compile(source.replace(exportLine, 'module.exports = async function handler('), file); + const res = { + statusCode: null, + body: null, + setHeader() {}, + status(code) { this.statusCode = code; return this; }, + json(body) { this.body = body; return this; }, + }; + const cwd = process.cwd(); + try { + process.chdir(dir); + await mod.exports({ query: {} }, res); + } finally { + process.chdir(cwd); + } + assert.equal(res.statusCode, 200, `the route answered ${res.statusCode}: ${JSON.stringify(res.body)}`); + return res.body; +} + +// pages/index.js compiled by the compiler `next build` uses, with the named +// components exported for the test, so the real dashboard markup is checked. +async function dashboard(...names) { + const swc = require('next/dist/build/swc'); + await swc.loadBindings(); + const file = join(ROOT, 'pages', 'index.js'); + const source = `${readFileSync(file, 'utf8')}\nexport { ${names.join(', ')} };\n`; + const { code } = await swc.transform(source, { + filename: file, + jsc: { parser: { syntax: 'ecmascript', jsx: true }, transform: { react: { runtime: 'automatic' } }, target: 'es2020' }, + module: { type: 'commonjs' }, + }); + const mod = new Module(file); + mod.filename = file; + mod.paths = Module._nodeModulePaths(join(ROOT, 'pages')); + mod._compile(code, file); + return mod.exports; +} + +function render(component, props) { + const { createElement } = require('react'); + const { renderToStaticMarkup } = require('react-dom/server'); + return renderToStaticMarkup(createElement(component, props)); +} + +const text = (html) => html.replace(/<[^>]+>/g, '').replace(/&/g, '&').trim(); + +// The tool table's body rows, each as its cells' text. +function tableRows(html) { + const body = /([\s\S]*?)<\/tbody>/.exec(html); + assert.ok(body, 'the tool table renders'); + return [...body[1].matchAll(/]*>([\s\S]*?)<\/tr>/g)] + .map(r => [...r[1].matchAll(/]*>([\s\S]*?)<\/td>/g)].map(c => text(c[1]))); +} + +// Each KPI card's label, value and whether a change figure is rendered. +function kpis(html) { + return html.split('
').slice(1).map(card => ({ + label: text(/
([\s\S]*?)<\/div>/.exec(card)[1]), + value: text(/
([\s\S]*?)<\/div>/.exec(card)[1]), + sub: text((/
([\s\S]*?)<\/div>/.exec(card) || ['', ''])[1]), + delta: /class="delta /.test(card), + })); +} + +function snapshot(over = {}) { + return { + asOf: '2026-11-02', generatedAt: '', provenance: '', retentionDays: 90, wauWindowDays: 7, mauWindowDays: 30, + totalInstalls: 400, wau: 120, mau: 340, engagedMau: 60, engagedMinDays: 2, + wauGrowth7d: null, mauGrowth30d: null, engagedGrowth30d: null, + ...over, + }; +} + +const withheldTool = (tool, versions = [{ version: '1.0.0', installs: null }]) => ( + { tool, product: tool, totalInstalls: null, wau: null, mau: null, engagedMau: null, versions } +); + +test('normalizeAdoptionFeed keeps a tool row whose figures are withheld and floors every count under ten to null', () => { + const { normalizeAdoptionFeed } = require(join(ROOT, 'lib', 'telemetry.js')); + const n = normalizeAdoptionFeed({ + totalInstalls: 0, wau: 9, mau: 10, engagedMau: null, + tools: [ + { tool: 'tool-a', totalInstalls: null, wau: null, mau: null, engagedMau: null, versions: [{ version: '1.0.0', installs: null }] }, + { tool: 'tool-b', totalInstalls: 0, wau: 1, mau: 9, engagedMau: 0, versions: [{ version: '2.0.0', installs: 3 }] }, + { tool: 'tool-c', totalInstalls: 12, wau: 10, mau: 11, engagedMau: 10, versions: [{ version: '3.0.0', installs: 10 }] }, + { tool: 'tool-x', totalInstalls: 'many', wau: 10, mau: 10, engagedMau: 10 }, // not a figure: dropped + ], + byCountry: [{ countryCode: 'AA', installs: 4 }, { countryCode: 'BB', installs: 25 }], + }); + assert.deepStrictEqual( + [n.totalInstalls, n.wau, n.mau, n.engagedMau], [null, null, 10, null], + 'fleet: 0 and 9 and a withheld figure are null, 10 is kept' + ); + assert.deepStrictEqual(n.tools.map(t => t.tool), ['tool-a', 'tool-b', 'tool-c'], 'the withheld row is kept, the untrusted one dropped'); + assert.deepStrictEqual(n.tools.map(t => [t.totalInstalls, t.wau, t.mau, t.engagedMau]), [ + [null, null, null, null], + [null, null, null, null], + [12, 10, 11, 10], + ]); + assert.deepStrictEqual(n.tools.map(t => t.versions), [ + [{ version: '1.0.0', installs: null }], + [{ version: '2.0.0', installs: null }], + [{ version: '3.0.0', installs: 10 }], + ]); + assert.deepStrictEqual(n.byCountry, [{ countryCode: 'AA', installs: null }, { countryCode: 'BB', installs: 25 }]); +}); + +test('normalizeAdoptionFeed accepts a fleet whose totals are all withheld, and still rejects one that omits them', () => { + const { normalizeAdoptionFeed } = require(join(ROOT, 'lib', 'telemetry.js')); + const n = normalizeAdoptionFeed({ totalInstalls: null, wau: null, mau: null, engagedMau: null, tools: [] }); + assert.deepStrictEqual([n.totalInstalls, n.wau, n.mau, n.engagedMau], [null, null, null, null]); + assert.throws(() => normalizeAdoptionFeed({ wau: null, mau: null }), /fleet totals/, 'a missing total is not a withheld one'); + assert.throws(() => normalizeAdoptionFeed({ totalInstalls: 50, wau: 20, mau: 30, engagedMau: 'x' }), /engagedMau/); +}); + +test('a feed whose per-tool totalInstalls, wau, mau and engagedMau are null keeps the row through the store, the API and the dashboard, each cell reading "fewer than 10", never 0', async () => { + const dir = tmp('chain'); + try { + mkdirSync(join(dir, 'data')); + const dbFile = storeAt(join(dir, 'data', 'analytics.db'), NOT_NULL_SCHEMA); + const run = await collect({ + generatedAt: '2026-11-02T00:00:00Z', provenance: 'synthetic feed', retentionDays: 90, wauWindowDays: 7, + mauWindowDays: 30, totalInstalls: 400, wau: 120, mau: 340, engagedMau: 60, engagedMinDays: 2, + tools: [ + { tool: 'tool-a', totalInstalls: null, wau: null, mau: null, engagedMau: null, versions: [{ version: '1.0.0', installs: null }] }, + { tool: 'tool-b', totalInstalls: 300, wau: 110, mau: 300, engagedMau: 55, versions: [{ version: '2.0.0', installs: 250 }] }, + ], + byCountry: [], + }, dbFile); + assert.equal(run.status, 0, `the collection is stored; output:\n${run.stdout}\n${run.stderr}`); + + const body = await serveTelemetry(dir); + const a = body.tools.find(t => t.tool === 'tool-a'); + assert.ok(a, `the API keeps the row whose figures are withheld; served: ${JSON.stringify(body.tools.map(t => t.tool))}`); + for (const field of ['totalInstalls', 'wau', 'mau', 'engagedMau']) { + assert.strictEqual(a[field], null, `${field} is served as null, never 0`); + } + assert.deepStrictEqual(a.versions, [{ version: '1.0.0', installs: null }]); + + const { TelemetrySection } = await dashboard('TelemetrySection'); + const row = tableRows(render(TelemetrySection, { data: body })).find(cells => cells[0].startsWith('tool-a')); + assert.ok(row, 'the dashboard keeps the row'); + assert.deepStrictEqual(row.slice(1), [LABEL, LABEL, LABEL, LABEL, `each version ${LABEL}`]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('the dashboard reads "fewer than 10" in every withheld cell, never 0, and states the rule once', async () => { + const { TelemetrySection } = await dashboard('TelemetrySection'); + const html = render(TelemetrySection, { + data: { + snapshot: snapshot({ totalInstalls: null, wau: null, mau: null, engagedMau: null, provenance: 'Synthetic provenance.' }), + tools: [ + { tool: 'tool-b', product: 'Tool B', totalInstalls: 300, wau: 110, mau: 300, engagedMau: 55, versions: [{ version: '2.0.0', installs: 250 }] }, + withheldTool('tool-a'), + ], + byCountry: [{ countryCode: 'BB', installs: 25 }, { countryCode: 'AA', installs: null }], + }, + }); + const cards = kpis(html); + assert.deepStrictEqual(cards.map(c => [c.label, c.value]), [ + ['Engaged monthly users', LABEL], + ['Reported MAU', LABEL], + ['Reported WAU', LABEL], + ]); + const rows = tableRows(html); + assert.deepStrictEqual(rows, [ + ['Tool Btool-b', '300', '55', '300', '110', '2.0.0 · 250'], + ['tool-a', LABEL, LABEL, LABEL, LABEL, `each version ${LABEL}`], + ]); + for (const cell of rows.flat()) assert.doesNotMatch(cell, /^0$|· 0$/, `no withheld cell reads 0: ${cell}`); + const chipRow = /
([\s\S]*?)<\/div>/.exec(html); + assert.ok(chipRow, 'the country chips render'); + const chips = chipRow[1].split(' text(p.slice(p.indexOf('>') + 1))); + assert.deepStrictEqual(chips, ['BB · 25', `AA · ${LABEL}`]); + assert.ok(text(html).includes(`Synthetic provenance. ${NOTE}`), 'the provenance carries the withheld note'); + assert.equal(text(html).split(NOTE).length - 1, 1, 'the note is stated once'); +}); + +test('the overview KPI reads "fewer than 10" for a withheld engaged or reported count, never 0', async () => { + const { ActiveCliUsersKpi } = await dashboard('ActiveCliUsersKpi'); + const [card] = kpis(render(ActiveCliUsersKpi, { snapshot: snapshot({ engagedMau: null, mau: null, engagedGrowth30d: 5 }) })); + assert.deepStrictEqual(card, { + label: 'Active CLI Users', value: LABEL, sub: `engaged monthly · ${LABEL} reported`, delta: false, + }); + const [measured] = kpis(render(ActiveCliUsersKpi, { snapshot: snapshot({ engagedMau: 60, mau: 340, engagedGrowth30d: 12 }) })); + assert.deepStrictEqual([measured.value, measured.sub, measured.delta], ['60', 'engaged monthly · 340 reported', true]); +}); + +test('a figure the dashboard computes leaves a withheld cell out: no change against a withheld side, no withheld version named as the top one', async () => { + const { TelemetrySection } = await dashboard('TelemetrySection'); + const html = render(TelemetrySection, { + data: { + // engaged 12 now, 7 a month ago (withheld): no change can be computed. + // MAU 330 now, 300 a month ago: both measured, so the change shows. + // WAU withheld now: no change either. + snapshot: snapshot({ engagedMau: 12, engagedGrowth30d: 5, mau: 330, mauGrowth30d: 30, wau: null, wauGrowth7d: 4 }), + tools: [{ + tool: 'tool-c', product: 'tool-c', totalInstalls: 80, wau: 20, mau: 60, engagedMau: 15, + // A withheld version listed first is never taken as the top one. + versions: [{ version: '2.0.0', installs: null }, { version: '1.1.0', installs: 15 }, { version: '1.0.0', installs: 40 }], + }], + byCountry: [], + }, + }); + assert.deepStrictEqual(kpis(html).map(c => [c.label, c.delta]), [ + ['Engaged monthly users', false], + ['Reported MAU', true], + ['Reported WAU', false], + ]); + assert.match(html, /\+10%/, 'the measured change is computed from measured values only'); + assert.deepStrictEqual(tableRows(html)[0][5], '1.0.0 · 40'); +}); + +test('/api/telemetry serves only floored counts, keeps every row, and orders a withheld row after the measured ones by name, never by the count it hides', async () => { + const dir = tmp('api'); + try { + mkdirSync(join(dir, 'data')); + // A store holding NULLs and, as an older store did, raw counts under ten. + storeAt(join(dir, 'data', 'analytics.db'), NULLABLE_SCHEMA, (db) => { + db.prepare('INSERT INTO telemetry_snapshots (date, total_installs, wau, mau, engaged_mau) VALUES (?, ?, ?, ?, ?)') + .run('2026-11-02', 0, 9, 120, null); + const tool = db.prepare('INSERT INTO telemetry_tool_snapshots (date, tool, total_installs, wau, mau, engaged_mau) VALUES (?, ?, ?, ?, ?, ?)'); + tool.run('2026-11-02', 'tool-c', 0, 20, 50, 12); + tool.run('2026-11-02', 'tool-a', null, null, null, null); + tool.run('2026-11-02', 'tool-b', 0, 3, 7, 1); + tool.run('2026-11-02', 'tool-d', 0, 1, 3, 0); + const version = db.prepare('INSERT INTO telemetry_version_snapshots (date, tool, version, installs) VALUES (?, ?, ?, ?)'); + version.run('2026-11-02', 'tool-c', '1.0.0', 30); + version.run('2026-11-02', 'tool-c', '1.1.0', 8); + version.run('2026-11-02', 'tool-c', '0.9.0', 4); + version.run('2026-11-02', 'tool-c', '0.8.0', null); + const country = db.prepare('INSERT INTO telemetry_country_snapshots (date, country_code, installs) VALUES (?, ?, ?)'); + country.run('2026-11-02', 'BB', 6); + country.run('2026-11-02', 'AA', 2); + country.run('2026-11-02', 'CC', 11); + }); + const body = await serveTelemetry(dir); + const s = body.snapshot; + assert.deepStrictEqual([s.totalInstalls, s.wau, s.mau, s.engagedMau], [null, null, 120, null]); + assert.deepStrictEqual(body.tools.map(t => [t.tool, t.totalInstalls, t.wau, t.mau, t.engagedMau]), [ + ['tool-c', null, 20, 50, 12], + ['tool-a', null, null, null, null], + ['tool-b', null, null, null, null], + ['tool-d', null, null, null, null], + ]); + assert.deepStrictEqual(body.tools[0].versions, [ + { version: '1.0.0', installs: 30 }, + { version: '0.8.0', installs: null }, + { version: '0.9.0', installs: null }, + { version: '1.1.0', installs: null }, + ]); + assert.deepStrictEqual(body.byCountry, [ + { countryCode: 'CC', installs: 11 }, + { countryCode: 'AA', installs: null }, + { countryCode: 'BB', installs: null }, + ]); + assert.deepStrictEqual(body.withheld, { below: 10, label: LABEL }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('the collector stores NULL for a withheld figure and for a count from 0 to 9, stores 10 or more as is, and keeps every row', async () => { + const dir = tmp('collect'); + try { + const dbFile = storeAt(join(dir, 'analytics.db'), NOT_NULL_SCHEMA); + const run = await collect({ + retentionDays: 90, wauWindowDays: 7, mauWindowDays: 30, engagedMinDays: 2, + totalInstalls: 0, wau: 9, mau: 10, engagedMau: null, + tools: [ + { + tool: 'tool-a', totalInstalls: null, wau: 1, mau: 9, engagedMau: 0, + versions: [{ version: '1.0.0', installs: null }, { version: '0.9.0', installs: 3 }, { version: '0.8.0', installs: 10 }], + }, + { tool: 'tool-b', totalInstalls: 12, wau: 10, mau: 11, engagedMau: 10, versions: [] }, + ], + byCountry: [{ countryCode: 'AA', installs: 4 }, { countryCode: 'BB', installs: 10 }], + }, dbFile); + assert.equal(run.status, 0, `output:\n${run.stdout}\n${run.stderr}`); + readOnly(dbFile, (db) => { + assert.deepStrictEqual(db.prepare('SELECT total_installs, wau, mau, engaged_mau FROM telemetry_snapshots').all(), [ + { total_installs: null, wau: null, mau: 10, engaged_mau: null }, + ]); + assert.deepStrictEqual( + db.prepare('SELECT tool, total_installs, wau, mau, engaged_mau FROM telemetry_tool_snapshots ORDER BY tool').all(), [ + { tool: 'tool-a', total_installs: null, wau: null, mau: null, engaged_mau: null }, + { tool: 'tool-b', total_installs: 12, wau: 10, mau: 11, engaged_mau: 10 }, + ] + ); + assert.deepStrictEqual(db.prepare('SELECT version, installs FROM telemetry_version_snapshots ORDER BY version').all(), [ + { version: '0.8.0', installs: 10 }, + { version: '0.9.0', installs: null }, + { version: '1.0.0', installs: null }, + ]); + assert.deepStrictEqual(db.prepare('SELECT country_code, installs FROM telemetry_country_snapshots ORDER BY country_code').all(), [ + { country_code: 'AA', installs: null }, + { country_code: 'BB', installs: 10 }, + ]); + for (const [table, cols] of Object.entries(COUNT_COLUMNS)) { + for (const c of db.prepare(`PRAGMA table_info(${table})`).all().filter(c => cols.includes(c.name))) { + assert.deepStrictEqual([c.notnull, c.dflt_value], [0, null], `${table}.${c.name} is nullable with no default`); + } + } + }); + assert.match( + run.stdout, + new RegExp(`Installs: ${LABEL} \\| WAU: ${LABEL} \\| MAU: 10 \\| engaged\\(MAU\\): ${LABEL} \\| tools: 2 \\| countries: 2`), + 'the public log line carries floored figures only' + ); + assert.equal(JSON.parse(readFileSync(join(dir, 'telemetry-badge.json'), 'utf8')).message, '10'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('the store step sets every stored count from 0 to 9 to withheld, zero included, keeps every row and every count of 10 or more, and changes nothing on a second run', async () => { + const dir = tmp('floor'); + try { + const dbFile = storeAt(join(dir, 'analytics.db'), NOT_NULL_SCHEMA, (db) => { + const fleet = db.prepare('INSERT INTO telemetry_snapshots (date, total_installs, wau, mau, engaged_mau) VALUES (?, ?, ?, ?, ?)'); + fleet.run('2026-10-01', 0, 3, 120, 9); + fleet.run('2026-10-02', 0, 15, 130, 40); + const tool = db.prepare('INSERT INTO telemetry_tool_snapshots (date, tool, total_installs, wau, mau, engaged_mau) VALUES (?, ?, ?, ?, ?, ?)'); + tool.run('2026-10-01', 'tool-a', 0, 1, 9, 0); + tool.run('2026-10-01', 'tool-b', 0, 25, 60, 12); + tool.run('2026-10-02', 'tool-a', 0, 10, 11, 2); + const version = db.prepare('INSERT INTO telemetry_version_snapshots (date, tool, version, installs) VALUES (?, ?, ?, ?)'); + version.run('2026-10-01', 'tool-a', '1.0.0', 4); + version.run('2026-10-01', 'tool-b', '2.0.0', 33); + version.run('2026-10-02', 'tool-a', '1.0.0', 0); + const country = db.prepare('INSERT INTO telemetry_country_snapshots (date, country_code, installs) VALUES (?, ?, ?)'); + country.run('2026-10-01', 'AA', 5); + country.run('2026-10-01', 'BB', 18); + }); + assert.deepStrictEqual(underTenCounts(dbFile), [3, 2, 1], 'the fixture holds counts under ten'); + + const first = await floorStore(dbFile); + assert.equal(first.status, 0, `output:\n${first.stdout}\n${first.stderr}`); + assert.deepStrictEqual(underTenCounts(dbFile), [0, 0, 0], 'per tool, per version and fleet: no count from 0 to 9 is left'); + readOnly(dbFile, (db) => { + assert.deepStrictEqual(db.prepare('SELECT date, total_installs, wau, mau, engaged_mau FROM telemetry_snapshots ORDER BY date').all(), [ + { date: '2026-10-01', total_installs: null, wau: null, mau: 120, engaged_mau: null }, + { date: '2026-10-02', total_installs: null, wau: 15, mau: 130, engaged_mau: 40 }, + ]); + assert.deepStrictEqual(db.prepare('SELECT date, tool, total_installs, wau, mau, engaged_mau FROM telemetry_tool_snapshots ORDER BY date, tool').all(), [ + { date: '2026-10-01', tool: 'tool-a', total_installs: null, wau: null, mau: null, engaged_mau: null }, + { date: '2026-10-01', tool: 'tool-b', total_installs: null, wau: 25, mau: 60, engaged_mau: 12 }, + { date: '2026-10-02', tool: 'tool-a', total_installs: null, wau: 10, mau: 11, engaged_mau: null }, + ]); + assert.deepStrictEqual(db.prepare('SELECT date, tool, version, installs FROM telemetry_version_snapshots ORDER BY date, tool').all(), [ + { date: '2026-10-01', tool: 'tool-a', version: '1.0.0', installs: null }, + { date: '2026-10-01', tool: 'tool-b', version: '2.0.0', installs: 33 }, + { date: '2026-10-02', tool: 'tool-a', version: '1.0.0', installs: null }, + ]); + assert.deepStrictEqual(db.prepare('SELECT country_code, installs FROM telemetry_country_snapshots ORDER BY country_code').all(), [ + { country_code: 'AA', installs: null }, + { country_code: 'BB', installs: 18 }, + ]); + for (const [table, cols] of Object.entries(COUNT_COLUMNS)) { + for (const c of db.prepare(`PRAGMA table_info(${table})`).all().filter(c => cols.includes(c.name))) { + assert.deepStrictEqual([c.notnull, c.dflt_value], [0, null], `${table}.${c.name} is nullable with no default`); + } + } + const indexes = db.prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE 'idx_telemetry_%' ORDER BY name").pluck().all(); + assert.deepStrictEqual(indexes, ['idx_telemetry_country_date', 'idx_telemetry_tool_date', 'idx_telemetry_version_date']); + }); + + const before = sha256(dbFile); + const second = await floorStore(dbFile); + assert.equal(second.status, 0, `output:\n${second.stdout}\n${second.stderr}`); + assert.equal(sha256(dbFile), before, 'a second run leaves the file byte for byte as it was'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('the store step refuses a table it could only rebuild by dropping a column, and leaves the store byte for byte as it was', async () => { + const dir = tmp('refuse'); + try { + const dbFile = storeAt( + join(dir, 'analytics.db'), + NOT_NULL_SCHEMA.replace('collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(date, tool)', 'note TEXT, collected_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(date, tool)'), + (db) => { + db.prepare('INSERT INTO telemetry_snapshots (date, total_installs, wau, mau, engaged_mau) VALUES (?, ?, ?, ?, ?)').run('2026-10-01', 0, 3, 120, 9); + db.prepare('INSERT INTO telemetry_tool_snapshots (date, tool, wau, note) VALUES (?, ?, ?, ?)').run('2026-10-01', 'tool-a', 4, 'kept'); + } + ); + const before = sha256(dbFile); + const run = await floorStore(dbFile); + assert.equal(run.status, 1, `output:\n${run.stdout}\n${run.stderr}`); + assert.match(run.stderr, /telemetry_tool_snapshots has columns the floored schema does not carry: note/); + assert.equal(sha256(dbFile), before, 'no table was rebuilt and no count was changed'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('on a copy of the committed store, the store step leaves no count from 0 to 9 per tool, per version or fleet, and keeps every row and every count of 10 or more', async () => { + const dir = tmp('committed'); + try { + const dbFile = join(dir, 'analytics.db'); + copyFileSync(join(ROOT, 'data', 'analytics.db'), dbFile); + const shape = (file) => readOnly(file, db => Object.entries(COUNT_COLUMNS).map(([table, cols]) => [ + table, + db.prepare(`SELECT count(*) FROM ${table}`).pluck().get(), + ...cols.map(c => db.prepare(`SELECT count(*) FROM ${table} WHERE ${c} >= 10`).pluck().get()), + ])); + const before = shape(dbFile); + const run = await floorStore(dbFile); + assert.equal(run.status, 0, `output:\n${run.stdout}\n${run.stderr}`); + assert.deepStrictEqual(underTenCounts(dbFile), [0, 0, 0]); + assert.deepStrictEqual(shape(dbFile), before, 'row counts and counts of 10 or more are unchanged'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('the store step rewrites the summary telemetry block from the floored store and leaves every other key as it was', async () => { + const dir = tmp('summary'); + try { + const dbFile = storeAt(join(dir, 'analytics.db'), NOT_NULL_SCHEMA, (db) => { + db.prepare('INSERT INTO telemetry_snapshots (date, provenance, total_installs, wau, mau, engaged_mau) VALUES (?, ?, ?, ?, ?, ?)') + .run('2026-11-02', 'synthetic', 0, 4, 120, 30); + db.prepare('INSERT INTO telemetry_tool_snapshots (date, tool, total_installs, wau, mau, engaged_mau) VALUES (?, ?, ?, ?, ?, ?)') + .run('2026-11-02', 'tool-a', 0, 2, 5, 1); + }); + const summaryFile = join(dir, 'summary.json'); + const summary = { + lastUpdated: '2026-11-02T06:10:00.000Z', + total: { + npm: 1234, + telemetry: { asOf: '2026-11-02', totalInstalls: 0, wau: 4, mau: 120, engagedMau: 30, tools: 1, countries: 0, provenance: 'synthetic' }, + chromeUsers: 50, + }, + series: { downloads: { value: 99 } }, + }; + writeFileSync(summaryFile, JSON.stringify(summary, null, 2)); + const run = await floorStore(dbFile, summaryFile); + assert.equal(run.status, 0, `output:\n${run.stdout}\n${run.stderr}`); + const out = JSON.parse(readFileSync(summaryFile, 'utf8')); + assert.deepStrictEqual(out.total.telemetry, { + asOf: '2026-11-02', totalInstalls: null, wau: null, mau: 120, engagedMau: 30, + withheld: { below: 10, label: LABEL }, tools: 1, countries: 0, provenance: 'synthetic', + }); + assert.deepStrictEqual({ ...out, total: { ...out.total, telemetry: null } }, { ...summary, total: { ...summary.total, telemetry: null } }); + assert.deepStrictEqual(Object.keys(out.total), Object.keys(summary.total), 'key order is kept'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('the summary builder publishes a telemetry count under ten, and a withheld one, as null, never as 0', () => { + const { buildSummary } = require(join(ROOT, 'lib', 'summary.js')); + const src = new Database(join(ROOT, 'data', 'analytics.db'), { readonly: true }); + const db = new Database(src.serialize()); + src.close(); + const dataDir = tmp('build'); + try { + // A fleet table with nullable counts holding synthetic rows. + db.exec('DROP TABLE telemetry_snapshots'); + db.exec(NULLABLE_SCHEMA.split(';')[0]); + db.prepare('INSERT INTO telemetry_snapshots (date, provenance, total_installs, wau, mau, engaged_mau) VALUES (?, ?, ?, ?, ?, ?)') + .run('2999-01-02', 'synthetic', null, 3, 120, null); + const t = buildSummary(db, { dataDir, env: {} }).total.telemetry; + assert.deepStrictEqual([t.asOf, t.totalInstalls, t.wau, t.mau, t.engagedMau], ['2999-01-02', null, null, 120, null]); + assert.deepStrictEqual(t.withheld, { below: 10, label: LABEL }); + } finally { + db.close(); + rmSync(dataDir, { recursive: true, force: true }); + } +}); diff --git a/test/telemetry.test.js b/test/telemetry.test.js index 59ba388d7..fb3e8e7de 100644 --- a/test/telemetry.test.js +++ b/test/telemetry.test.js @@ -76,7 +76,7 @@ test('normalizeAdoptionFeed passes a valid feed through', () => { test('normalizeAdoptionFeed defaults provenance + engagedMau when absent (never fabricated)', () => { const n = normalizeAdoptionFeed({ totalInstalls: 10, wau: 5, mau: 8 }); assert.equal(n.provenance, ''); - assert.equal(n.engagedMau, 0); // absent → 0, not invented + assert.strictEqual(n.engagedMau, null); // absent → withheld (null), never a 0 assert.equal(n.tools.length, 0); });