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
82 changes: 69 additions & 13 deletions pm-stack/cloudflare-export/cloudflare-quota-export.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,11 @@ export function classifyR2(groups) {
else if (R2_FREE.has(action)) continue;
else unclassified.push(action);
}
return { classA, classB, unclassified, nonbillable };
// Saturation (#6880): a result at the query limit may exclude
// further operation groups, so both class totals are lower bounds;
// the r2-storage discipline, applied to the operations dataset.
const saturated = groups.length >= R2_OPERATIONS_GROUP_LIMIT;
return { classA, classB, unclassified, nonbillable, saturated };
}

/** Fold KV action types onto the card's two metrics: reads, and
Expand Down Expand Up @@ -278,22 +282,55 @@ export function parseGraphqlUsage(
const push = (id, used, unit, extra = {}) =>
metrics.push({ id, used, unit, source: src, ...extra });

// Saturation discipline (#6880): every grouped dataset in
// GRAPHQL_QUERY carries an explicit limit; a result AT the limit
// may be truncated, so the affected metrics are flagged
// lowerBound — the r2-storage pattern below, applied to all of
// them. (The *Saturated locals are computed only after the
// fail-closed readers have validated the groups are arrays.)
const workers = account?.workersInvocationsAdaptive;
push("workers-requests", firstSum(workers, "requests", "workers"), "count");
push("workers-cpu-ms", Math.round(firstSum(workers, "cpuTimeUs", "workers") / 1000), "ms");
const workersRequests = firstSum(workers, "requests", "workers");
const workersCpuMs = Math.round(firstSum(workers, "cpuTimeUs", "workers") / 1000);
const workersSaturated = workers.length >= WORKERS_GROUP_LIMIT;
push("workers-requests", workersRequests, "count", {
...(workersSaturated ? { lowerBound: true } : {}),
});
push("workers-cpu-ms", workersCpuMs, "ms", {
...(workersSaturated ? { lowerBound: true } : {}),
});

const kv = foldKv(account?.kvOperationsAdaptiveGroups);
push("kv-reads", kv.reads, "count");
push("kv-writes", kv.writes, "count");
const kvGroups = account?.kvOperationsAdaptiveGroups;
const kv = foldKv(kvGroups);
const kvSaturated = kvGroups.length >= KV_GROUP_LIMIT;
push("kv-reads", kv.reads, "count", {
...(kvSaturated ? { lowerBound: true } : {}),
});
push("kv-writes", kv.writes, "count", {
...(kvSaturated ? { lowerBound: true } : {}),
});

push("d1-rows-read", firstSum(account?.d1AnalyticsAdaptiveGroups, "rowsRead", "d1"), "rows");
push("d1-rows-written", firstSum(account?.d1AnalyticsAdaptiveGroups, "rowsWritten", "d1"), "rows");
const d1Groups = account?.d1AnalyticsAdaptiveGroups;
const d1Saturated = Array.isArray(d1Groups) && d1Groups.length >= D1_GROUP_LIMIT;
push("d1-rows-read", firstSum(d1Groups, "rowsRead", "d1"), "rows", {
...(d1Saturated ? { lowerBound: true } : {}),
});
push("d1-rows-written", firstSum(d1Groups, "rowsWritten", "d1"), "rows", {
...(d1Saturated ? { lowerBound: true } : {}),
});

push("queues-ops", firstSum(account?.queueMessageOperationsAdaptiveGroups, "billableOperations", "queues"), "ops");
const queueGroups = account?.queueMessageOperationsAdaptiveGroups;
const queuesSaturated = Array.isArray(queueGroups) && queueGroups.length >= QUEUES_GROUP_LIMIT;
push("queues-ops", firstSum(queueGroups, "billableOperations", "queues"), "ops", {
...(queuesSaturated ? { lowerBound: true } : {}),
});

const r2 = classifyR2(account?.r2OperationsAdaptiveGroups);
push("r2-class-a", r2.classA, "ops");
push("r2-class-b", r2.classB, "ops");
push("r2-class-a", r2.classA, "ops", {
...(r2.saturated ? { lowerBound: true } : {}),
});
push("r2-class-b", r2.classB, "ops", {
...(r2.saturated ? { lowerBound: true } : {}),
});

const storageGroups = account?.r2StorageAdaptiveGroups;
if (!Array.isArray(storageGroups)) {
Expand Down Expand Up @@ -326,10 +363,17 @@ export function parseGraphqlUsage(
});

// Neurons are a fractional measurement (fixture total 4114515.31), not a request count: plain-decimal strings stay valid here.
const neuronsTotal = firstSum(account?.aiInferenceAdaptiveGroups, "totalNeurons", "ai", { integerString: false });
const aiGroups = account?.aiInferenceAdaptiveGroups;
const neuronsTotal = firstSum(aiGroups, "totalNeurons", "ai", { integerString: false });
const aiSaturated = aiGroups.length >= AI_NEURONS_GROUP_LIMIT;
const daysElapsed = Math.max(1, (now - cycleStart) / 86_400_000);
push("workers-ai-neurons", Math.round(neuronsTotal / daysElapsed), "neurons", {
detail: `per-day average over the cycle to date; cycle total ${Math.round(neuronsTotal)} neurons`,
...(aiSaturated ? { lowerBound: true } : {}),
detail:
`per-day average over the cycle to date; cycle total ${Math.round(neuronsTotal)} neurons` +
(aiSaturated
? ` — group count hit the ${AI_NEURONS_GROUP_LIMIT} query limit, so the cycle total (and this average) is a LOWER BOUND`
: ""),
});

// The average above stays for card compatibility; the per-day alert
Expand Down Expand Up @@ -436,6 +480,18 @@ function scopeError(what, status) {
// total as a lower bound if a result ever saturates it.
export const R2_STORAGE_GROUP_LIMIT = 10000;

// The remaining GRAPHQL_QUERY group limits (#6880). Each dataset's
// parser flags its metrics lowerBound when a result reaches its
// limit — the same discipline as r2-storage above — so no at-limit
// sum is ever published as an exact reading. Keep these in step with
// the `limit:` arguments in GRAPHQL_QUERY below.
export const WORKERS_GROUP_LIMIT = 100;
export const KV_GROUP_LIMIT = 100;
export const D1_GROUP_LIMIT = 100;
export const QUEUES_GROUP_LIMIT = 100;
export const R2_OPERATIONS_GROUP_LIMIT = 1000;
export const AI_NEURONS_GROUP_LIMIT = 100;

const GRAPHQL_QUERY = `query($a: string!, $s: Time!, $e: Time!) {
viewer {
accounts(filter: { accountTag: $a }) {
Expand Down
89 changes: 89 additions & 0 deletions pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@ import {
foldKv,
listR2Buckets,
parseGraphqlUsage,
AI_NEURONS_GROUP_LIMIT,
D1_GROUP_LIMIT,
KV_GROUP_LIMIT,
QUEUES_GROUP_LIMIT,
R2_OPERATIONS_GROUP_LIMIT,
R2_STORAGE_GROUP_LIMIT,
WORKERS_GROUP_LIMIT,
run,
successDocument,
} from "./cloudflare-quota-export.mjs";
Expand Down Expand Up @@ -178,6 +184,89 @@ test("parseGraphqlUsage: r2-storage total covers every bucket group, saturation
assert.equal(coveredById["r2-storage"].lowerBound, undefined);
});

// #6880: every grouped dataset with an explicit query limit flags
// its metrics lowerBound at the limit (the r2-storage pattern) and
// stays unflagged one below it — no at-limit sum publishes as exact.
const SATURATION_CASES = [
{
dataset: "workersInvocationsAdaptive",
limit: WORKERS_GROUP_LIMIT,
group: () => ({ sum: { requests: 1, cpuTimeUs: 1000 } }),
metricIds: ["workers-requests", "workers-cpu-ms"],
},
{
dataset: "kvOperationsAdaptiveGroups",
limit: KV_GROUP_LIMIT,
group: () => ({ dimensions: { actionType: "read" }, sum: { requests: 1 } }),
metricIds: ["kv-reads", "kv-writes"],
},
{
dataset: "d1AnalyticsAdaptiveGroups",
limit: D1_GROUP_LIMIT,
group: () => ({ sum: { rowsRead: 1, rowsWritten: 1 } }),
metricIds: ["d1-rows-read", "d1-rows-written"],
},
{
dataset: "queueMessageOperationsAdaptiveGroups",
limit: QUEUES_GROUP_LIMIT,
group: () => ({ sum: { billableOperations: 1 } }),
metricIds: ["queues-ops"],
},
{
dataset: "r2OperationsAdaptiveGroups",
limit: R2_OPERATIONS_GROUP_LIMIT,
group: () => ({ dimensions: { actionType: "GetObject" }, sum: { requests: 1 } }),
metricIds: ["r2-class-a", "r2-class-b"],
},
{
dataset: "aiInferenceAdaptiveGroups",
limit: AI_NEURONS_GROUP_LIMIT,
group: () => ({ sum: { totalNeurons: 10 } }),
metricIds: ["workers-ai-neurons"],
},
];

for (const { dataset, limit, group, metricIds } of SATURATION_CASES) {
test(`parseGraphqlUsage: ${dataset} at its query limit flags lowerBound (#6880)`, () => {
const atLimit = structuredClone(ACCOUNT);
atLimit[dataset] = Array.from({ length: limit }, group);
const satById = Object.fromEntries(
parseGraphqlUsage(atLimit, { now: NOW, cycleStart: START }).metrics.map((m) => [m.id, m]),
);
for (const id of metricIds) assert.equal(satById[id].lowerBound, true, id);

const belowLimit = structuredClone(ACCOUNT);
belowLimit[dataset] = Array.from({ length: limit - 1 }, group);
const belowById = Object.fromEntries(
parseGraphqlUsage(belowLimit, { now: NOW, cycleStart: START }).metrics.map((m) => [m.id, m]),
);
for (const id of metricIds) assert.equal(belowById[id].lowerBound, undefined, id);
});
}

test("classifyR2: saturation is reported for r2OperationsAdaptiveGroups (#6880)", () => {
const groups = Array.from({ length: R2_OPERATIONS_GROUP_LIMIT }, () => ({
dimensions: { actionType: "GetObject" },
sum: { requests: 1 },
}));
const atLimit = classifyR2(groups);
assert.equal(atLimit.saturated, true);
assert.equal(atLimit.classB, R2_OPERATIONS_GROUP_LIMIT);
assert.equal(classifyR2(groups.slice(1)).saturated, false);
});

test("parseGraphqlUsage: ai cycle-total saturation is flagged in prose too (#6880)", () => {
const atLimit = structuredClone(ACCOUNT);
atLimit.aiInferenceAdaptiveGroups = Array.from({ length: AI_NEURONS_GROUP_LIMIT }, () => ({
sum: { totalNeurons: 10 },
}));
const byId = Object.fromEntries(
parseGraphqlUsage(atLimit, { now: NOW, cycleStart: START }).metrics.map((m) => [m.id, m]),
);
assert.equal(byId["workers-ai-neurons"].lowerBound, true);
assert.match(byId["workers-ai-neurons"].detail, /LOWER BOUND/);
});

test("classifyR2/foldKv: a missing groups field fails closed, not zero", () => {
assert.throws(() => classifyR2(undefined), /r2OperationsAdaptiveGroups missing/);
assert.throws(() => classifyR2(null), /r2OperationsAdaptiveGroups missing/);
Expand Down
Loading