From 846fa3fcebb3e702db71b8beaff1c63d8b18ab91 Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Wed, 25 Nov 2026 17:31:51 -0700 Subject: [PATCH] perf(metering): a daily fleet job stores closed months' totals; shard deletion moves into it, off for now Reads no longer delete a closed month's shards. The job does, under its lease, behind MeteringService.DELETE_CLOSED_SHARDS (false): a version that sums the shards reports a deleted month as zero. --- doc/self-hosting.md | 5 +- src/backend/services/jobs/systemJobs.test.ts | 6 ++ .../services/metering/MeteringService.test.ts | 35 +++++++- .../services/metering/MeteringService.ts | 87 ++++++++++++------- 4 files changed, 99 insertions(+), 34 deletions(-) diff --git a/doc/self-hosting.md b/doc/self-hosting.md index 54444d4e4..e11dfe4d3 100644 --- a/doc/self-hosting.md +++ b/doc/self-hosting.md @@ -469,9 +469,8 @@ belong to, 3 by default. Set it to `0` to keep every month's records forever: Changing it, including to `0`, applies to records first written after the change; records already stamped keep their expiry. -The total across all accounts is the exception: a day after a month ends, its -total is stored as one record that never expires, and the per-month counters -it was summed from are deleted. +The total across all accounts is the exception: once a month has ended, a +daily job stores its total as one record that never expires. ### Captcha on signup / login diff --git a/src/backend/services/jobs/systemJobs.test.ts b/src/backend/services/jobs/systemJobs.test.ts index 89722d3e5..170b410a0 100644 --- a/src/backend/services/jobs/systemJobs.test.ts +++ b/src/backend/services/jobs/systemJobs.test.ts @@ -64,6 +64,12 @@ const EXPECTED_JOBS = { nearPrimary: false, leaseMs: 5 * MINUTE, }, + 'metering.closeGlobalMonths': { + every: 24 * HOUR, + scope: 'fleet', + nearPrimary: false, + leaseMs: 30 * MINUTE, + }, 'events.subscriptions.expirySweep': { every: HOUR, scope: 'fleet', diff --git a/src/backend/services/metering/MeteringService.test.ts b/src/backend/services/metering/MeteringService.test.ts index a0b024185..ea78b78f1 100644 --- a/src/backend/services/metering/MeteringService.test.ts +++ b/src/backend/services/metering/MeteringService.test.ts @@ -13,6 +13,7 @@ import murmurhash from 'murmurhash'; import type { Actor } from '../../core/actor.ts'; import { SYSTEM_ACTOR, makeActor as resolveActor } from '../../core/actor.ts'; import { PuterServer } from '../../server.ts'; +import { testJobContext } from '../jobs/jobsTestUtil.ts'; import { bucketTag } from '../../stores/metering/MeteringBufferStore.ts'; import { setupTestServer } from '../../testUtil.ts'; import { @@ -3576,7 +3577,7 @@ describe('MeteringService', () => { expect(res).toMatchObject({ total: sum }); // The stored total stands whatever the shards say afterwards, - // and they are kept until the delete delay has passed. + // and a read deletes none of them. await server.stores.kv.set({ key: shardKey(0, month), value: { total: 9999 }, @@ -3586,7 +3587,22 @@ describe('MeteringService', () => { expect(await liveShards(month)).toBe(ctor().GLOBAL_SHARD_COUNT); }); - it('deletes the shards once the stored total is old enough', async () => { + it('the job stores a total nothing has read', async () => { + const month = '1997-03'; + await seedShards(month, 4); + + await target.closeGlobalMonths(); + await drainAux(); + + const { res } = await server.stores.kv.get({ + key: totalKey(month), + }); + expect(res).toMatchObject({ + total: 4 * ctor().GLOBAL_SHARD_COUNT, + }); + }); + + it('only the job deletes the shards, once the stored total is old enough', async () => { const month = '1997-02'; const pageItems = ctor().CLOSED_SHARD_DELETE_PAGE_ITEMS; const unitsPerSecond = @@ -3597,7 +3613,9 @@ describe('MeteringService', () => { ctor().CLOSED_SHARD_DELETE_PAGE_ITEMS = pageItems; ctor().CLOSED_SHARD_DELETE_UNITS_PER_SECOND = unitsPerSecond; + ctor().DELETE_CLOSED_SHARDS = false; }); + const count = ctor().GLOBAL_SHARD_COUNT; await seedShards(month, 7); await server.stores.kv.set({ key: totalKey(month), @@ -3608,9 +3626,22 @@ describe('MeteringService', () => { }, }); + // Off by default: neither a read nor the job deletes. + await target.closeGlobalMonths(); + expect(await liveShards(month)).toBe(count); + + ctor().DELETE_CLOSED_SHARDS = true; expect((await target.getGlobalUsage(month)).total).toBe(1234); await drainAux(); + expect(await liveShards(month)).toBe(count); + // A run that lost the job stops before its next batch. + const lost = testJobContext(); + lost.abort(); + await target.closeGlobalMonths(lost.signal); + expect(await liveShards(month)).toBe(count); + + await target.closeGlobalMonths(testJobContext().signal); expect(await liveShards(month)).toBe(0); expect((await target.getGlobalUsage(month)).total).toBe(1234); }); diff --git a/src/backend/services/metering/MeteringService.ts b/src/backend/services/metering/MeteringService.ts index 80e3e0794..673f4d502 100644 --- a/src/backend/services/metering/MeteringService.ts +++ b/src/backend/services/metering/MeteringService.ts @@ -133,6 +133,11 @@ const GLOBAL_RATE_CHECK_JOB = 'metering.globalRateCheck'; const GLOBAL_RATE_CHECK_EVERY_MS = 25 * 60 * 1000; const GLOBAL_RATE_CHECK_LEASE_MS = 5 * 60 * 1000; +/** Stores closed months' global totals whether or not anything reads them. */ +const GLOBAL_MONTH_CLOSE_JOB = 'metering.closeGlobalMonths'; +const GLOBAL_MONTH_CLOSE_EVERY_MS = 24 * 60 * 60 * 1000; +const GLOBAL_MONTH_CLOSE_LEASE_MS = 30 * 60 * 1000; + // -- Helpers ---------------------------------------------------------- /** @@ -205,6 +210,12 @@ export class MeteringService extends PuterService { * buffered counters and replication between deployments. */ static GLOBAL_MONTH_CLOSE_GRACE_MS = 24 * 60 * 60 * 1000; + /** + * Off until every version a deployment can roll back to reads stored month + * totals: an older one sums the shards, and reports a deleted month as + * zero. + */ + static DELETE_CLOSED_SHARDS = false; /** * How long a stored month total stands before its shards are deleted, so no * sweep that began without the total sums a partly deleted month. @@ -338,8 +349,6 @@ export class MeteringService extends PuterService { * a call's aux writes instead of guessing with a sleep. */ private pendingAuxPromises = new Set>(); - /** One closed-shard deletion per process at a time. */ - #deletingClosedShards = false; /** Uuid → resolved policy + expiry; `lookupFailed` marks a fallback. */ private subscriptionCache = new BoundedTtlMap< @@ -463,6 +472,13 @@ export class MeteringService extends PuterService { }, ); + this.services.jobs.register(GLOBAL_MONTH_CLOSE_JOB, { + every: GLOBAL_MONTH_CLOSE_EVERY_MS, + scope: 'fleet', + leaseMs: GLOBAL_MONTH_CLOSE_LEASE_MS, + run: ({ signal }) => this.closeGlobalMonths(signal), + }); + const maxPerMinute = this.config.maxGlobalUsagePerMinute; if (maxPerMinute && maxPerMinute > 0) { this.services.jobs.register(GLOBAL_RATE_CHECK_JOB, { @@ -2570,10 +2586,28 @@ export class MeteringService extends PuterService { * bytes read, where getting each shard by key is charged per key. * * A month past `GLOBAL_MONTH_CLOSE_GRACE_MS` is summed once: the first read - * stores its total, later reads answer from that item, and its shards are - * deleted in the background. + * stores its total and later reads answer from that item. */ async getGlobalUsageByMonth(): Promise> { + return (await this.#sweepGlobalUsage()).totals; + } + + /** + * The daily job: a sweep, which stores the total of each month that closed + * since the last one, then the deletion of shards a stored total replaced. + * Deleting only here keeps it to the one process holding the job. + */ + async closeGlobalMonths(signal?: AbortSignal): Promise { + const { replaced } = await this.#sweepGlobalUsage(); + if (MeteringService.DELETE_CLOSED_SHARDS) + await this.#deleteClosedShards(replaced, signal); + } + + /** Every month's total, and the shard keys a stored total has replaced. */ + async #sweepGlobalUsage(): Promise<{ + totals: Map; + replaced: string[]; + }> { const now = Date.now(); const totals = new Map(); const stored = new Map(); @@ -2645,11 +2679,10 @@ export class MeteringService extends PuterService { for (const key of keys) replaced.push(key); } } - this.#deleteClosedShards(replaced); // A stored total is final: shards still listed beside it are leftovers. for (const [month, { total }] of stored) totals.set(month, total); - return totals; + return { totals, replaced }; } /** Whether `month` (`YYYY-MM`) ended at least the close grace ago. */ @@ -2664,30 +2697,26 @@ export class MeteringService extends PuterService { } /** Deletes shards a stored month total replaced, paced by write units. */ - #deleteClosedShards(keys: string[]): void { - if (this.#deletingClosedShards || keys.length === 0) return; - this.#deletingClosedShards = true; + async #deleteClosedShards( + keys: string[], + signal?: AbortSignal, + ): Promise { const pageItems = MeteringService.CLOSED_SHARD_DELETE_PAGE_ITEMS; - const run = async () => { - try { - for (let i = 0; i < keys.length; i += pageItems) { - const startedAt = Date.now(); - const { usage } = await this.stores.kv.batchDel({ - keys: keys.slice(i, i + pageItems), - }); - const waitMs = - (usage.write / - MeteringService.CLOSED_SHARD_DELETE_UNITS_PER_SECOND) * - 1000 - - (Date.now() - startedAt); - if (i + pageItems < keys.length && waitMs > 0) - await sleep(waitMs, undefined, { ref: false }); - } - } finally { - this.#deletingClosedShards = false; - } - }; - this.handleAuxPromise('closedGlobalShards', run()); + for (let i = 0; i < keys.length; i += pageItems) { + // The rest are listed again by the next run. + if (signal?.aborted) return; + const startedAt = Date.now(); + const { usage } = await this.stores.kv.batchDel({ + keys: keys.slice(i, i + pageItems), + }); + const waitMs = + (usage.write / + MeteringService.CLOSED_SHARD_DELETE_UNITS_PER_SECOND) * + 1000 - + (Date.now() - startedAt); + if (i + pageItems < keys.length && waitMs > 0) + await sleep(waitMs, undefined, { ref: false }); + } } async updateAddonCredit(