Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 33 additions & 24 deletions lib/summary.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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';

Expand All @@ -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();
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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 };
89 changes: 89 additions & 0 deletions lib/telemetry-withheld.js
Original file line number Diff line number Diff line change
@@ -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,
};
103 changes: 72 additions & 31 deletions lib/telemetry.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -42,54 +44,86 @@ 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
* is better than a fabricated one, and a bad feed must not overwrite good data
* 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 {
Expand All @@ -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,
Expand Down Expand Up @@ -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 —
Expand All @@ -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. '
Expand All @@ -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
),
};
Expand Down
Loading
Loading