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
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,16 +113,24 @@ npm run collect:pypi-countries -- --dry-run
```

This issues only BigQuery dry runs, which are not billed, prints each day's scan size against
both caps, and writes nothing. It exits 0 only when the next run would clear both caps.
both caps, and writes nothing. It exits 0 only when the next run would clear both caps. When
every day in the window is already fetched, the next run bills nothing; the dry run then
measures yesterday as a sample and reports whether a new day of that size would clear both caps.
`npm run collect:pypi-countries --dry-run` (without the `--`) is also a dry run. Any other
argument after the `--` is refused with a usage message and exit code 2. A flag given without
the `--` goes to npm, not to the collector's arguments, so a mistyped
`npm run collect:pypi-countries --dryrun` is not refused: the run collects as normal.

## Automated daily collection

The included workflow (`.github/workflows/collect-stats.yml`) runs daily at `6:00 AM UTC`. To enable it:

1. Settings → Secrets and variables → Actions → New secret.
2. Add `GH_STATS_TOKEN` (a Personal Access Token with `repo` or `public_repo` scope).
3. Optionally set `GOOGLE_APPLICATION_CREDENTIALS_JSON` for BigQuery country stats.
4. Optionally set the `REGISTRY_URL` Actions **variable** to enable first-party CLI telemetry collection. Unset, the collector warns and skips.
3. Optionally set the `REGISTRY_URL` Actions **variable** to enable first-party CLI telemetry collection. Unset, the collector warns and skips.

The workflow does not collect BigQuery country stats, so it needs no Google Cloud credentials;
run `npm run collect:pypi-countries` where your credentials are (see above).

### When telemetry collection stops

Expand Down
115 changes: 86 additions & 29 deletions scripts/collect-pypi-country-stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
* Per run it fetches at most three missing closed days (newest first, from the
* 30 most recent closed days; no backfill beyond that window), lands the rows
* in pypi_country_daily keyed by the closed day itself, then rewrites the
* 30-day rollup in pypi_country_downloads as a local SUM — no query.
* 30-day rollup in pypi_country_downloads as a local SUM — no query. A run
* that stops early (a cap, a refusal, an error) still rewrites the rollup
* when it landed at least one day.
*
* Every run ends by persisting data/pypi-country-run.json with a status from
* {ok, empty, skipped_no_credentials, refused_cap, capped_month, error}. A
Expand All @@ -24,7 +26,11 @@
* only the dry runs for the days the next run would fetch, reports each scan
* size against both caps, and bills nothing and writes nothing (no rows, no
* ledger, no run status). It exits 0 only when the next run would clear both
* caps.
* caps; when every candidate day is already fetched, it measures D-1 as a
* sample and exits 0 only when a new day of that size would clear them.
* npm_config_dry_run=true, which npm sets for
* `npm run collect:pypi-countries --dry-run`, selects it as well; any other
* argument exits 2 with a usage message before anything runs.
*
* The client port this module consumes: one async `query(options)` that
* resolves to { rows, totalBytesProcessed } for both dry and billed runs. A
Expand Down Expand Up @@ -212,14 +218,24 @@ function readBudget(dataDir, month) {
* pypi_country_fetch_days whose fetch ran that month. The store is committed
* with the collected days and the ledger file is not, so on a fresh checkout
* this is the month-to-date figure that survived. 0 before the table exists.
* Fail closed: a total that is not a non-negative integer throws rather than
* reading as 0.
* Fail closed: a day of the month whose figure is not a non-negative integer
* throws, since a negative or text figure would lower the sum, and so does a
* total that is not one, rather than reading as 0.
*/
function storeMonthBytes(db, month) {
const table = db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='pypi_country_fetch_days'"
).get();
if (!table) return 0;
const { unreadable } = db.prepare(`
SELECT COUNT(*) AS unreadable
FROM pypi_country_fetch_days
WHERE substr(fetched_at, 1, 7) = ?
AND (typeof(bytes_billed) != 'integer' OR bytes_billed < 0)
`).get(month);
if (unreadable > 0) {
throw new Error(`unreadable billed-bytes figure on ${unreadable} day(s) of ${month} in pypi_country_fetch_days`);
}
const { total } = db.prepare(`
SELECT COALESCE(SUM(bytes_billed), 0) AS total
FROM pypi_country_fetch_days
Expand All @@ -233,10 +249,11 @@ function storeMonthBytes(db, month) {
}

/**
* Month-to-date billed bytes: the larger of the ledger file and the store.
* The ledger also holds the reservation of a billed call that failed, so it
* is the higher figure whenever it survived; the store is the floor when it
* did not.
* Month-to-date billed bytes: the larger of the ledger file and the store,
* because either one can be stale. The ledger file is not committed, so a
* checkout may lack it or carry one older than the store's fetch records;
* the store never sees the reservation the ledger keeps for a billed call
* that failed. Taking the larger can over-count, never under-count.
*/
function monthToDate(db, dataDir, month) {
return Math.max(readBudget(dataDir, month), storeMonthBytes(db, month));
Expand Down Expand Up @@ -422,6 +439,12 @@ async function collect({
});

let rowsLanded = 0;
// A run that stops early still rolls up the days it already landed, so
// the 30-day total never lags the daily rows.
const stop = (status) => finish(status, {
asOf: daysFetched > 0 ? rollupCountryDownloads(db, now) : newestStoredDay(db),
daysFetched, bytesBilled: runBytes, exitCode: 1,
});
for (const day of missingDays) {
const dayIso = isoDay(day);
const options = buildDayQueryOptions(packages, day);
Expand All @@ -433,22 +456,16 @@ async function collect({
const estimate = readByteFigure(dry.totalBytesProcessed);
if (estimate === null) {
log('Refusing %s: unreadable dry-run estimate (%s)', dayIso, String(dry.totalBytesProcessed));
return finish('error', {
asOf: newestStoredDay(db), daysFetched, bytesBilled: runBytes, exitCode: 1,
});
return stop('error');
}
if (estimate > PER_QUERY_CAP_BYTES) {
log('Refusing %s: dry run estimates %d bytes, over the per-query cap', dayIso, estimate);
return finish('refused_cap', {
asOf: newestStoredDay(db), daysFetched, bytesBilled: runBytes, exitCode: 1,
});
return stop('refused_cap');
}
if (monthBytes + estimate > MONTH_CAP_BYTES) {
log('Refusing %s: month-to-date %d + estimate %d bytes would pass the monthly cap',
dayIso, monthBytes, estimate);
return finish('capped_month', {
asOf: newestStoredDay(db), daysFetched, bytesBilled: runBytes, exitCode: 1,
});
return stop('capped_month');
}

// Reservation: charge the estimate to the ledger BEFORE the billed call.
Expand All @@ -470,9 +487,7 @@ async function collect({
writeBudget(dataDir, month, monthBytes, now);
log('Refusing %s: BigQuery refused the job at the %d byte ceiling; nothing was billed',
dayIso, PER_QUERY_CAP_BYTES);
return finish('refused_cap', {
asOf: newestStoredDay(db), daysFetched, bytesBilled: runBytes, exitCode: 1,
});
return stop('refused_cap');
}
const billedBytes = readByteFigure(billed.totalBytesProcessed);
// An unreadable, negative or non-integer billed figure charges the
Expand All @@ -497,7 +512,14 @@ async function collect({
} catch (error) {
console.error('PyPI country collection failed: %s', error.message);
let asOf = null;
try { if (db) asOf = newestStoredDay(db); } catch { /* keep null */ }
if (db) {
// Days that landed before the failure still reach the rollup.
try {
asOf = daysFetched > 0 ? rollupCountryDownloads(db, now) : newestStoredDay(db);
} catch {
try { asOf = newestStoredDay(db); } catch { /* keep null */ }
}
}
return finish('error', { asOf, daysFetched, bytesBilled: runBytes, exitCode: 1 });
} finally {
if (db) db.close();
Expand All @@ -518,7 +540,9 @@ function gib(bytes) {
* monthToDateBytes, perQueryCapBytes, monthCapBytes, exitCode } with status
* from {estimated, refused_cap, capped_month, skipped_no_credentials, error};
* exitCode is 0 only for estimated. When every candidate day is already
* fetched, D-1 is measured as a sample with fetched: true.
* fetched, the next run bills nothing; D-1 is then measured as a sample with
* fetched: true, and the status and exitCode are the verdict for a new day
* of that size, not for the next run.
*/
async function estimate({
client = null,
Expand Down Expand Up @@ -594,11 +618,22 @@ async function estimate({
monthBytes += bytes;
}
const result = finish(status);
log('Per-query cap %s GiB; month to date %s GiB billed, these queries add %s GiB of the %s GiB monthly cap.',
gib(PER_QUERY_CAP_BYTES), gib(monthToDateBytes), gib(result.estimatedBytes), gib(MONTH_CAP_BYTES));
log(status === 'estimated'
? 'The next run would clear both caps.'
: `The next run would be refused (${status}).`);
log('Per-query cap %s GiB; month to date %s GiB billed, %s %s GiB of the %s GiB monthly cap.',
gib(PER_QUERY_CAP_BYTES), gib(monthToDateBytes),
sample ? 'a new day of this size would add' : 'these queries add',
gib(result.estimatedBytes), gib(MONTH_CAP_BYTES));
if (sample) {
// The next run selects no day, so no cap can refuse it; the verdict is
// a prediction for the next day that closes.
log('The next run would bill nothing: every candidate day is already fetched.');
log(status === 'estimated'
? 'A new day of this size would clear both caps.'
: `A new day of this size would be refused (${status}).`);
} else {
log(status === 'estimated'
? 'The next run would clear both caps.'
: `The next run would be refused (${status}).`);
}
return result;
} catch (error) {
console.error('PyPI country dry run failed: %s', error.message);
Expand All @@ -608,11 +643,33 @@ async function estimate({
}
}

const USAGE = 'Usage: npm run collect:pypi-countries -- [--dry-run]';

/**
* Read the command line. `--dry-run` is the only argument; anything else is
* refused, never read as a request for a billed collection. Without the `--`
* separator, `npm run collect:pypi-countries --dry-run` keeps the flag for
* npm, which passes it on as npm_config_dry_run=true, so that is a dry run
* too. Returns { dryRun } or { error }.
*/
function parseArgs(argv, env = process.env) {
const unknown = argv.filter(arg => arg !== '--dry-run');
if (unknown.length > 0) {
return { error: `Unrecognised argument(s): ${unknown.join(' ')}` };
}
return { dryRun: argv.includes('--dry-run') || env.npm_config_dry_run === 'true' };
}

async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.error) {
console.error(args.error);
console.error(USAGE);
process.exit(2);
}
require('dotenv').config();
console.log('PyPI Country Download Stats Collector (BigQuery)');
const dryRun = process.argv.slice(2).includes('--dry-run');
const result = dryRun ? await estimate({}) : await collect({});
const result = args.dryRun ? await estimate({}) : await collect({});
process.exit(result.exitCode);
}

Expand Down
106 changes: 104 additions & 2 deletions test/pypi-country-collector.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ const { test } = require('node:test');
const assert = require('node:assert');
const { spawn } = require('node:child_process');
const { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } = require('node:fs');
const { join } = require('node:path');
const { join, dirname } = require('node:path');
const { tmpdir } = require('node:os');
const Database = require('better-sqlite3');

const {
collect,
estimate,
PER_QUERY_CAP_BYTES,
MONTH_CAP_BYTES,
BUDGET_FILE,
Expand Down Expand Up @@ -317,6 +318,30 @@ test('an unreadable billed total in the store is an error that bills nothing, ne
}
});

for (const [label, figures] of [
['a negative day', [5000, -1000]],
['a non-numeric day', [5000, 'abc']],
['a negative and a non-numeric day', [5000, -1000, 'abc']],
]) {
test(`a month whose fetch records hold ${label} is an error, never a lower month-to-date`, async () => {
const dir = tmp();
try {
const dbPath = makeStore(dir, { fetchedDays: ALL_CANDIDATES.filter(d => d !== dayBefore(1)) });
figures.forEach((bytes, i) => recordBilled(dbPath, [dayBefore(i + 2)], bytes, '2026-09-01T06:00:00.000Z'));
const client = fakeClient();
const res = await runCollect(dbPath, client);
assert.equal(res.status, 'error', 'the per-day figures must not sum to a total below the 5000 billed');
assert.equal(res.exitCode, 1);
assert.equal(client.calls.length, 0, 'nothing is estimated or billed against an unreadable month');
const dry = await estimate({ client, dbPath, now: NOW, env: {}, log: noop });
assert.equal(dry.status, 'error');
assert.equal(client.calls.length, 0);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
}

test('GAT-01.AC3 an unparseable ledger starts the month at 0 rather than failing', async () => {
const dir = tmp();
try {
Expand Down Expand Up @@ -485,18 +510,79 @@ test('GAT-01.AC5 a day 31 days old is excluded from the rollup sum', async () =>
}
});

/**
* Client for a run over two missing days: D-1 bills and lands one row, then
* D-2 stops the run through `second` (its dry-run figure, or the error its
* billed call rejects with).
*/
function secondDayStops(second) {
return {
async query(options) {
const isSecond = callDay(options) === dayBefore(2);
if (options.dryRun) {
return { rows: [], totalBytesProcessed: isSecond && 'dryBytes' in second ? second.dryBytes : 1000 };
}
if (isSecond) throw second.billedError;
return { rows: [{ project: 'aim-sdk', country_code: 'DE', downloads: 7 }], totalBytesProcessed: 1000 };
},
};
}

const ceilingRefusal = () => Object.assign(new Error('Query exceeded limit for bytes billed'), {
code: 400, errors: [{ reason: 'bytesBilledLimitExceeded', message: 'Query exceeded limit for bytes billed' }],
});

for (const [label, status, second, ledger] of [
['BigQuery refuses its billed job at the ceiling', 'refused_cap', { billedError: ceilingRefusal() }],
['its dry run is over the per-query cap', 'refused_cap', { dryBytes: PER_QUERY_CAP_BYTES + 1 }],
['its estimate would pass the monthly cap', 'capped_month', { dryBytes: 1000 }, MONTH_CAP_BYTES - 1500],
['its dry run is unreadable', 'error', { dryBytes: 'abc' }],
['its billed call fails', 'error', { billedError: new Error('backend error') }],
]) {
test(`a run that lands D-1 and stops because ${label} still rolls D-1 into the 30-day total`, async () => {
const dir = tmp();
try {
const dbPath = makeStore(dir, {
fetchedDays: ALL_CANDIDATES.filter(d => d !== dayBefore(1) && d !== dayBefore(2)),
});
if (ledger !== undefined) {
writeFileSync(join(dir, BUDGET_FILE), JSON.stringify({ month: '2026-09', bytesBilled: ledger }));
}
const res = await runCollect(dbPath, secondDayStops(second));
assert.equal(res.status, status);
assert.equal(res.exitCode, 1);
assert.equal(res.daysFetched, 1);
assert.equal(res.asOf, dayBefore(1));
assert.equal(readStatus(dir).asOf, dayBefore(1));
const db = new Database(dbPath, { readonly: true });
const rows = db.prepare('SELECT package_id, date, country_code, downloads FROM pypi_country_downloads').all();
db.close();
assert.deepEqual(rows, [{ package_id: 5, date: dayBefore(1), country_code: 'DE', downloads: 7 }],
'the landed day is in the rollup, not only in pypi_country_daily');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
}

// ---------------------------------------------------------------------------
// AC7 — scheduled run without credentials exits 1; population needs no env
// ---------------------------------------------------------------------------

/**
* Run the collector CLI against the store in a temporary directory. The child
* runs in that directory, so the .env it loads is the test's, never the one
* at the repository root, which may hold real BigQuery credentials.
*/
function runScript(extraEnv, dbPath) {
return new Promise((resolve) => {
const env = { ...process.env, ANALYTICS_DB_PATH: dbPath, ...extraEnv };
delete env.GOOGLE_APPLICATION_CREDENTIALS;
delete env.GOOGLE_CLOUD_PROJECT;
delete env.PYPI_PACKAGES;
delete env.npm_config_dry_run;
if (!extraEnv.GITHUB_ACTIONS) delete env.GITHUB_ACTIONS;
const child = spawn(process.execPath, [SCRIPT], { env });
const child = spawn(process.execPath, [SCRIPT], { env, cwd: dirname(dbPath) });
let stdout = '';
let stderr = '';
child.stdout.on('data', (d) => (stdout += d));
Expand All @@ -517,6 +603,22 @@ test('GAT-01.AC7 a scheduled run without credentials persists skipped_no_credent
}
});

test('the spawned collector loads .env from the test directory, not the repository root', async () => {
const dir = tmp();
try {
const dbPath = makeStore(dir);
// A key path that does not exist: the collector names it and still
// never reaches BigQuery.
const missingKey = join(dir, 'no-such-key.json');
writeFileSync(join(dir, '.env'), `GOOGLE_APPLICATION_CREDENTIALS=${missingKey}\n`);
const res = await runScript({}, dbPath);
assert.ok(res.stdout.includes(missingKey), `the test directory's .env was not loaded; stdout:\n${res.stdout}`);
assert.equal(readStatus(dir).status, 'skipped_no_credentials');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

test('GAT-01.AC7 the same credential skip outside Actions exits 0 with the same status', async () => {
const dir = tmp();
try {
Expand Down
Loading
Loading