From f82b925d827a2658bcbc7e0d83e71e4f1cd49ddb Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sun, 8 Nov 2026 10:52:18 -0500 Subject: [PATCH 1/3] Add bounded durable window cleanup for scheduled hosts --- README.md | 52 ++- docs/PROJECT_PLAN.md | 43 +- packages/rate-limit/README.md | 81 +++- packages/rate-limit/package.json | 2 +- .../rate-limit/src/durable-sweep-page.test.ts | 440 ++++++++++++++++++ packages/rate-limit/src/durable.ts | 111 ++++- packages/rate-limit/src/index.ts | 3 + 7 files changed, 719 insertions(+), 13 deletions(-) create mode 100644 packages/rate-limit/src/durable-sweep-page.test.ts diff --git a/README.md b/README.md index 49b4b33..9e3a6f5 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,16 @@ in-memory tier and a durable storage-backed tier for expensive operations. > [!IMPORTANT] > Rate Limit is in early `0.x` development. Its public API is not stable. -> `@pegma/rate-limit@0.1.0` is the first advertised release, published from -> the protected signed `v0.1.0` tag through trusted-publisher OIDC with -> provenance. pegma.dev composes the durable tier in its production Identity -> worker. +> Current source is the **`0.3.0` candidate, not published**. Registry `0.2.0` +> predates the merged [PR #8 hardening](https://github.com/pegma-dev/rate-limit/pull/8) +> and the new bounded maintenance helper. The first advertised `0.1.0` +> release was published from protected signed `v0.1.0` through +> trusted-publisher OIDC with provenance; the historical `0.0.0` name bootstrap +> remains separate under `bootstrap`. pegma.dev composes the durable tier in +> its production Identity worker; this candidate is not a new host deployment. + +The source behavior below describes the `0.3.0` candidate. Adoption waits for +its reviewed publication and the host's explicit configuration/storage transition. ## Two tiers, no pretending @@ -49,6 +55,44 @@ Conflicting instances fail closed; rolling configuration changes use a versioned policy name or a coordinated store reset. Sweeps retain ended windows for a configurable clock-skew grace, 60 seconds by default. +## Bounded global durable maintenance (source candidate) + +`sweepDurableWindowsPage` is exported from the package root and +`@pegma/rate-limit/durable`. It takes a Store and a required physical page +`limit`, optional opaque `cursor`, `clock`, and `maxClockSkewMs`, returning +`{ scanned, deleted, nextCursor }`. The +[source definition](packages/rate-limit/src/durable.ts) owns the exact types. +This is maintenance across all policies in that Store's rate-limit collection; +it requires no policy enumeration or live limiter instances. + +Each call makes one scan of at most `limit` physical rows, including policy +descriptors, unrelated policies, malformed records, and unknown legacy rows. +It validates the page bound before filtering or keyed work, then makes at most +`limit` fresh descriptor reads and `limit` conditional deletes. Only a valid +new-format expired window whose identity matches its actual scan key, current +policy descriptor, and unchanged opaque version can be deleted. Descriptors, +legacy `0.2.0` rows, malformed rows, and policy mismatches remain stored. + +The host persists the returned cursor unchanged after a successful page, +including a page that deletes nothing. On rejection it retains the previous +cursor and retries later; no completed page is reported. Pages are not +snapshots, so repeat complete cycles. The helper applies its configured +clock-skew grace across the page, 60 seconds by default; choose a common grace +consistent with the host's peer-clock envelope. The helper itself leaves the +already-merged memory behavior, `allow()`, and per-policy `limiter.sweep()` +unchanged. + +## Published `0.2.0` storage and configuration + +Published `0.2.0` predates immutable policy descriptors and the new +`kind`/`limit`/`windowMs` counter layout. The candidate does not automatically +convert or clean up those legacy rows. Plan a versioned policy name or a +separate Store namespace, or coordinate a deliberate reset of the affected +policy storage. Do not silently reuse an old layout or overwrite a descriptor +to change limits. A new namespace/reset starts a separate count budget; the +host must plan the transition rather than assume old and new counts combine. +See the [package migration notes](packages/rate-limit/README.md#migrating-storage-and-policy-configuration). + Fixed windows have a documented edge: a burst crossing a boundary can briefly admit nearly twice the configured limit. This package does not claim to be DDoS or volumetric protection, and it does not provide HTTP middleware or diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index aa03bcd..e2d0e3c 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -3,10 +3,14 @@ ## Status **Stage:** Phases 1, 2, and 4 are complete; Phase 3 has its first production -consumer. `@pegma/rate-limit@0.1.1` is published, and pegma.dev composes the -durable tier for its Identity surface. `0.2.0` is prepared, aligning -`@pegma/storage-core` at `0.4.0` across the stack. The public API remains -unstable. +consumer. Registry `@pegma/rate-limit@0.2.0` is published, and pegma.dev composes +the durable tier for its Identity surface. Current source is the **`0.3.0` +candidate, not published**, retaining exact Storage Core `0.4.0`. Published +`0.2.0` predates the already-merged [PR #8 hardening](https://github.com/pegma-dev/rate-limit/pull/8) +for immutable policy descriptors, counter kind/configuration bindings, and +clock-skew grace. The candidate includes that hardening plus bounded global +maintenance. The public API remains unstable; source completion is not a +publication or host-adoption receipt. The exact reviewed `0.0.0` package-name bootstrap remains published under `bootstrap`. The first advertised `0.1.0` release was published from the @@ -183,6 +187,37 @@ collection over an injected Store). The memory tier must remain importable without a Store — a host wanting only abuse-dampening should not construct storage. TypeScript, vitest, the ecosystem's standard layout. +## `0.3.0` bounded-maintenance source candidate + +`sweepDurableWindowsPage` is a root/durable export over the existing +`rate-limit-windows` collection. One call makes one physical global scan page, +bounded by the required `limit`, with at most that many fresh descriptor reads +and version-conditional deletes. Every returned row counts before filtering; +there is no policy enumeration or unbounded list behind the page API. + +Only structurally valid new-format expired windows whose identity matches the +actual scan key and current immutable descriptor are deletion candidates. +The exact captured window version must still match. Descriptors, legacy +`0.2.0` layouts, malformed rows, and unknown/mismatched policy state remain. +Grace defaults to 60 seconds and is explicit host configuration across the +global pass. Adding this helper leaves the already-merged memory-tier and +existing `allow()`/per-policy sweep behavior unchanged. + +Hosts own cursor retention and scheduling. Preserve the opaque continuation +after each successful page, including no-deletion pages; retain the previous +cursor after an error. Pages are not snapshots, so repeat full cycles. The +[source API](../packages/rate-limit/src/durable.ts) and +[package contract](../packages/rate-limit/README.md#bounded-global-cleanup) +define the interface; current-head gates, review, exact publication, and host +adoption remain release work. + +Upgrading existing durable data is deliberate: use versioned policy names or +an isolated Store namespace, or coordinate a policy-store reset. Immutable +descriptors bind `limit` and `windowMs`; neither conflicting configuration nor +the old published layout is silently rewritten or reused. The global helper +retains legacy rows rather than migrating them. New namespaces/resets do not +carry over or aggregate old counters automatically. + ## Delivery phases ### Phase 1 — port and memory tier diff --git a/packages/rate-limit/README.md b/packages/rate-limit/README.md index 4d96bc4..a0e1c1f 100644 --- a/packages/rate-limit/README.md +++ b/packages/rate-limit/README.md @@ -9,11 +9,17 @@ Two explicitly named application rate-limit tiers: abuse-critical operations. > [!IMPORTANT] -> `0.1.0` is the first advertised release, published through +> Current source is the **`0.3.0` candidate, not published**. Published `0.2.0` +> predates the merged descriptor/configuration hardening and the bounded +> global sweep described here. `0.1.0` was the first advertised release, published through > trusted-publisher OIDC with provenance. The exact reviewed `0.0.0` > package-name bootstrap remains isolated under the `bootstrap` dist-tag and > is never advertised as the current supported release. +The API and storage behavior below describe candidate source. Use an exact +published version only after its release verification and an explicit host +storage/configuration transition. + There is no default tier and no automatic upgrade. This package is application abuse control, not DDoS protection, HTTP middleware, or billing metering. Policy names and limiter keys must be primitive, non-blank strings. Whitespace @@ -107,14 +113,83 @@ The durable tier uses fixed windows. A burst across a boundary can briefly admit nearly twice the limit. It also puts shared-storage latency on every allowed check; do not use it for hot, cheap endpoints. -Sweeps list one policy partition and delete structurally valid expired rows +The existing `limiter.sweep()` lists one policy partition and deletes structurally valid expired rows only if their versions are unchanged. By default a row remains for 60 seconds after its window ends; `maxClockSkewMs` can set a different bounded, non-negative grace for hosts with a known clock envelope. Malformed rows are retained: -storage-core listings do not expose actual row keys, so pairing a malformed +that partition-listing API does not expose actual row keys, so pairing a malformed row's version with a key reconstructed from its payload could target another row. Checks against that malformed row still fail closed. +## Bounded global cleanup + +The candidate adds this interface at the root and durable subpath, defined in +[the actual source](src/durable.ts): + +```ts +export declare function sweepDurableWindowsPage( + store: Store, + options: DurableWindowsSweepOptions, +): Promise; +``` + +`options.limit` is required: a safe integer from 1 through Storage Core's +`MAX_SCAN_PAGE_SIZE` (1,000). Other options are an opaque nonempty `cursor`, +an optional Spine `clock`, and non-negative safe-integer `maxClockSkewMs`. +The result is `{ scanned: number, deleted: number, nextCursor: string | null }`. +This is a source API signature, not an execution example or publication receipt. + +One call scans one global physical page of `rate-limit-windows`, without a +policy filter, partition enumeration, `list`, or `listVersioned`. `scanned` +counts every adapter-returned row before filtering, even descriptors, unknown +legacy layouts, malformed rows, and policies the current host no longer +constructs. An oversized/invalid physical page rejects before descriptor reads +or deletes. There are at most `limit` fresh descriptor reads and `limit` +`deleteIfUnchanged` calls. + +Deletion requires a structurally valid new-format `window` with valid hashes, +canonical window ID, aligned start, count within its stored limit, and a safe +expiry. Its decoded partition/ID must match the actual scan key. The current +descriptor is read by that authoritative key for each candidate and must match +the exact policy kind/key/hash, descriptor null fields, `limit`, and `windowMs`. +Only the captured unchanged window version is deleted. This is conditional +maintenance, not an atomic snapshot across descriptors and windows. + +Expiry is `windowStartMs + windowMs + maxClockSkewMs <= now`. The clock must +return a canonical timestamp; the sum must be a safe integer. The default +grace is 60,000 ms; explicit zero is supported. The global helper applies its +own grace to every policy it encounters, so the host chooses one that covers +its peer-clock envelope. Descriptors, legacy `0.2.0` rows, malformed windows, +unknown kinds, missing/mismatched descriptors, and changed window versions are +retained. + +Persist `nextCursor` unchanged only after success, including pages with no +deletions. Null ends that cycle; it does not prove no concurrent/new rows exist. +Repeat complete cycles for ongoing hygiene. Storage or time failures reject +without a completed page or new cursor; retain the previous cursor on failure. +The helper itself does not change the already-merged memory behavior, +`allow()` admission, or the existing per-policy sweep. + +## Migrating storage and policy configuration + +Registry `0.2.0` is older than the descriptor and `kind`/`limit`/`windowMs` +hardening already merged on main. Sharing its version label or policy name +does not make legacy counter rows compatible with this candidate. Neither +the limiter nor global cleanup silently migrates the old layout; unknown +legacy rows remain, and malformed encountered counter state fails closed. + +Select versioned policy names or a separate Store namespace for the new +configuration, or coordinate an explicit reset of the affected policy storage. +New names/namespaces and resets start independent count budgets; plan the +cutover and old-data retention rather than assuming counts carry over or add +together across deployments. The package supplies no automatic migration/reset. + +Once a descriptor exists, its policy name is bound immutably to `limit` and +`windowMs`. Changing either requires another versioned name or a coordinated +reset; conflicting instances fail closed. Do not edit descriptors in place, +delete arbitrary malformed rows, or mistake the global sweep for a migration +of previously published `0.2.0` data. + ## License MIT diff --git a/packages/rate-limit/package.json b/packages/rate-limit/package.json index 4d67c08..1ad059f 100644 --- a/packages/rate-limit/package.json +++ b/packages/rate-limit/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/rate-limit", - "version": "0.2.0", + "version": "0.3.0", "description": "Explicit per-instance sliding-window and shared durable fixed-window rate limiters.", "license": "MIT", "type": "module", diff --git a/packages/rate-limit/src/durable-sweep-page.test.ts b/packages/rate-limit/src/durable-sweep-page.test.ts new file mode 100644 index 0000000..c137f20 --- /dev/null +++ b/packages/rate-limit/src/durable-sweep-page.test.ts @@ -0,0 +1,440 @@ +import { randomUUID } from "node:crypto"; +import { TableClient } from "@azure/data-tables"; +import { createAzureTablesStore } from "@pegma/storage-azure-tables"; +import { + createMemoryStore, + defineCollection, + type CollectionDefinition, + type CollectionStore, + type EntityKey, + type ScanRecord, + type Store, + type StoredRecord, + type StoredValue, +} from "@pegma/storage-core"; +import { describe, expect, it } from "vitest"; +import { TABLE_PORT } from "../../../test/azurite.js"; +import { createDurableLimiter, sweepDurableWindowsPage } from "./durable.js"; + +const connection = + "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;" + + "AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;" + + `TableEndpoint=http://127.0.0.1:${TABLE_PORT}/devstoreaccount1;`; +const start = "2026-01-01T00:00:00.000Z"; +const expired = "2026-01-01T00:02:00.000Z"; +const clock = { now: () => expired }; + +function azurite(): Store { + const client = TableClient.fromConnectionString( + connection, + `rlpage${randomUUID().replaceAll("-", "")}`, + { allowInsecureConnection: true }, + ); + return createAzureTablesStore({ client }); +} +const stores: Array<[string, () => Store]> = [ + ["memory", createMemoryStore], + ["Azurite", azurite], +]; + +function raw( + store: Store, + physicalKey?: EntityKey, +): CollectionStore { + return store.collection( + defineCollection({ + name: "rate-limit-windows", + key: (value) => + physicalKey ?? { + partition: String(value.partition), + id: String(value.id), + }, + codec: { + encode: (value) => ({ ...value }), + decode: (value) => ({ ...value }), + }, + }), + ); +} +async function rows(store: Store): Promise[]> { + const result: ScanRecord[] = []; + let cursor: string | undefined; + for (let page = 0; page < 100; page += 1) { + const current = await raw(store).scan({ + limit: 100, + ...(cursor === undefined ? {} : { cursor }), + }); + result.push(...current.records); + if (current.nextCursor === null) return result; + cursor = current.nextCursor; + } + throw new Error("Fixture scan exceeded its finite bound."); +} +async function seed( + store: Store, + name: string, + keys: readonly string[] = ["old"], + at = start, +) { + const limiter = createDurableLimiter( + { name, limit: 3, windowMs: 60_000 }, + store, + ); + for (const key of keys) + expect(await limiter.allow(key, at)).toEqual({ allowed: true }); + return limiter; +} +function field(value: StoredRecord, name: string): number { + const result = value[name]; + if (typeof result !== "number") + throw new Error("Expected a numeric window field."); + return result; +} +interface Hooks { + readonly oversized?: boolean; + readonly fail?: "scan" | "descriptor" | "delete"; + readonly beforeDelete?: (key: EntityKey) => Promise; + readonly afterDelete?: () => Promise; +} +function observed(inner: Store, hooks: Hooks = {}) { + const scans: number[] = []; + let gets = 0; + let deletes = 0; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const collection = inner.collection(definition); + return { + ...collection, + async scan(options) { + scans.push(options.limit); + if (hooks.fail === "scan") throw new Error("scan unavailable"); + return collection.scan( + hooks.oversized + ? { ...options, limit: options.limit + 1 } + : options, + ); + }, + async getVersioned(key) { + gets += 1; + if (hooks.fail === "descriptor") + throw new Error("descriptor unavailable"); + return collection.getVersioned(key); + }, + async deleteIfUnchanged(key, version) { + deletes += 1; + if (hooks.fail === "delete") throw new Error("delete unavailable"); + await hooks.beforeDelete?.(key); + const deleted = await collection.deleteIfUnchanged(key, version); + await hooks.afterDelete?.(); + return deleted; + }, + async list() { + throw new Error("Unbounded list is forbidden in paged cleanup."); + }, + async listVersioned() { + throw new Error( + "Unbounded listVersioned is forbidden in paged cleanup.", + ); + }, + }; + }, + }; + return { store, scans, gets: () => gets, deletes: () => deletes }; +} + +describe.each(stores)( + "global bounded durable cleanup over %s", + (_name, makeStore) => { + it("counts every physical row and follows no-match pages across policies and legacy rows", async () => { + const backing = makeStore(); + await seed(backing, "old-one"); + await seed(backing, "unrelated-old-policy"); + await seed( + backing, + "live-policy", + ["future"], + "2026-01-01T00:10:00.000Z", + ); + await raw(backing).put({ + partition: "unrelated", + id: "legacy", + policyHash: "legacy", + subjectHash: "legacy", + windowStartMs: 0, + count: 1, + }); + await raw(backing).put({ + partition: "unrelated", + id: "malformed", + kind: "window", + count: -1, + }); + await raw(backing).put({ + partition: "unrelated", + id: "unknown", + kind: "future-record", + }); + const before = await rows(backing); + const track = observed(backing); + let cursor: string | undefined; + let scanned = 0; + let deleted = 0; + let noMatchContinuation = false; + let completed = false; + for (let page = 0; page < 100; page += 1) { + const result = await sweepDurableWindowsPage(track.store, { + limit: 1, + clock, + ...(cursor === undefined ? {} : { cursor }), + }); + expect(result.scanned).toBeLessThanOrEqual(1); + scanned += result.scanned; + deleted += result.deleted; + if (result.deleted === 0 && result.nextCursor !== null) + noMatchContinuation = true; + if (result.nextCursor === null) { + completed = true; + break; + } + cursor = result.nextCursor; + } + expect(completed).toBe(true); + expect(noMatchContinuation).toBe(true); + expect(scanned).toBe(before.length); + expect(deleted).toBe(2); + expect((await rows(backing)).length).toBe(before.length - 2); + expect(track.scans.every((limit) => limit === 1)).toBe(true); + expect(track.gets()).toBeLessThanOrEqual(scanned); + expect(track.deletes()).toBe(2); + expect( + (await rows(backing)).filter((row) => row.value.kind === "policy"), + ).toHaveLength(3); + }); + + it("rejects physical over-return before descriptor reads or deletes", async () => { + const backing = makeStore(); + await seed(backing, "physical-budget"); + const track = observed(backing, { oversized: true }); + await expect( + sweepDurableWindowsPage(track.store, { limit: 1, clock }), + ).rejects.toThrow("bounded scan page"); + expect(track.scans).toEqual([1]); + expect(track.gets()).toBe(0); + expect(track.deletes()).toBe(0); + expect(await rows(backing)).toHaveLength(2); + }); + + it("retains malformed/new-format identities and never pairs a payload key with another row's version", async () => { + const backing = makeStore(); + await seed(backing, "malformed-windows", [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + ]); + const windows = (await rows(backing)).filter( + (row) => row.value.kind === "window", + ); + expect(windows).toHaveLength(8); + for (const [index, row] of windows.entries()) { + const value: Record = { ...row.value }; + if (index === 0) value.count = 0; + if (index === 1) value.count = field(value, "limit") + 1; + if (index === 2) value.limit = field(value, "limit") + 1; + if (index === 3) value.windowMs = field(value, "windowMs") * 2; + if (index === 4) { + // Fully valid payload at the wrong physical key must not even attempt + // a conditional delete using the payload's reconstructed victim key. + await raw(backing).delete(row.key); + await raw(backing, { + partition: row.key.partition, + id: `${row.key.id}-miskey`, + }).put(value); + continue; + } + if (index === 5) { + delete value.kind; + delete value.limit; + delete value.windowMs; + } + if (index === 6) value.kind = "unknown-future-kind"; + if (index === 7) { + const offset = field(value, "windowStartMs") + 1; + value.windowStartMs = offset; + value.id = `${offset}-${String(value.subjectHash)}`; + await raw(backing).delete(row.key); + await raw(backing).put(value); + } else await raw(backing, row.key).put(value); + } + const before = await rows(backing); + const track = observed(backing); + expect( + await sweepDurableWindowsPage(track.store, { limit: 100, clock }), + ).toEqual({ scanned: 9, deleted: 0, nextCursor: null }); + expect(await rows(backing)).toEqual(before); + expect(track.deletes()).toBe(0); + expect(track.gets()).toBeLessThanOrEqual(9); + }); + + it("requires the actual current policy descriptor for every expired window", async () => { + const backing = makeStore(); + for (const name of ["missing", "malformed", "mismatched"]) + await seed(backing, name); + const descriptors = (await rows(backing)).filter( + (row) => row.value.kind === "policy", + ); + for (const [index, descriptor] of descriptors.entries()) { + if (index === 0) await raw(backing).delete(descriptor.key); + else + await raw(backing, descriptor.key).put({ + ...descriptor.value, + ...(index === 1 ? { subjectHash: "unexpected" } : { limit: 99 }), + }); + } + const before = await rows(backing); + const track = observed(backing); + expect( + await sweepDurableWindowsPage(track.store, { limit: 100, clock }), + ).toEqual({ scanned: 5, deleted: 0, nextCursor: null }); + expect(await rows(backing)).toEqual(before); + expect(track.gets()).toBe(3); + expect(track.deletes()).toBe(0); + }); + + it("preserves default clock-skew grace and permits an explicit zero grace", async () => { + const backing = makeStore(); + await seed(backing, "skew"); + expect( + await sweepDurableWindowsPage(backing, { + limit: 100, + clock, + maxClockSkewMs: Number.MAX_SAFE_INTEGER, + }), + ).toEqual({ scanned: 2, deleted: 0, nextCursor: null }); + expect( + await sweepDurableWindowsPage(backing, { + limit: 100, + clock: { now: () => "2026-01-01T00:01:59.999Z" }, + }), + ).toEqual({ scanned: 2, deleted: 0, nextCursor: null }); + expect( + await sweepDurableWindowsPage(backing, { limit: 100, clock }), + ).toEqual({ scanned: 2, deleted: 1, nextCursor: null }); + await seed(backing, "no-grace"); + expect( + await sweepDurableWindowsPage(backing, { + limit: 100, + clock: { now: () => "2026-01-01T00:01:00.000Z" }, + maxClockSkewMs: 0, + }), + ).toEqual({ scanned: 3, deleted: 1, nextCursor: null }); + }); + + it("does not delete a window after an actual concurrent allow increments its scanned version", async () => { + const backing = makeStore(); + const limiter = await seed(backing, "raced", ["same"]); + const track = observed(backing, { + beforeDelete: async () => { + expect(await limiter.allow("same", start)).toEqual({ allowed: true }); + }, + }); + expect( + await sweepDurableWindowsPage(track.store, { limit: 100, clock }), + ).toEqual({ scanned: 2, deleted: 0, nextCursor: null }); + expect(track.deletes()).toBe(1); + expect(await limiter.allow("same", start)).toEqual({ allowed: true }); + expect((await limiter.allow("same", start)).allowed).toBe(false); + }); + + it("re-reads descriptor authority between candidates instead of caching a stale policy", async () => { + const backing = makeStore(); + await seed(backing, "descriptor-race", ["first", "second"]); + const descriptor = (await rows(backing)).find( + (row) => row.value.kind === "policy", + ); + if (descriptor === undefined) + throw new Error("Expected a real policy descriptor."); + let changed = false; + const track = observed(backing, { + afterDelete: async () => { + if (!changed) { + changed = true; + await raw(backing, descriptor.key).put({ + ...descriptor.value, + limit: 99, + }); + } + }, + }); + expect( + await sweepDurableWindowsPage(track.store, { limit: 100, clock }), + ).toEqual({ scanned: 3, deleted: 1, nextCursor: null }); + expect(track.gets()).toBe(2); + expect(track.deletes()).toBe(1); + }); + + it.each(["scan", "descriptor", "delete"] as const)( + "rejects %s failures without reporting a completed page", + async (fail) => { + const backing = makeStore(); + await seed(backing, "failed-page"); + const track = observed(backing, { fail }); + await expect( + sweepDurableWindowsPage(track.store, { limit: 100, clock }), + ).rejects.toThrow("unavailable"); + expect(await rows(backing)).toHaveLength(2); + }, + ); + }, +); + +describe("bounded cleanup input failures", () => { + it.each([0, -1, 1.5, 1001, Number.NaN, Number.POSITIVE_INFINITY])( + "rejects invalid physical limit %s before scanning", + async (limit) => { + const track = observed(createMemoryStore()); + await expect( + sweepDurableWindowsPage(track.store, { limit, clock }), + ).rejects.toThrow("limit"); + expect(track.scans).toEqual([]); + }, + ); + it.each(["01/01/2026", "not-a-time"])( + "rejects malformed/noncanonical time %s before scanning", + async (at) => { + const track = observed(createMemoryStore()); + await expect( + sweepDurableWindowsPage(track.store, { + limit: 1, + clock: { now: () => at }, + }), + ).rejects.toThrow("clock"); + expect(track.scans).toEqual([]); + }, + ); + it("rejects a failed clock or invalid skew without claiming an empty completed page", async () => { + const track = observed(createMemoryStore()); + await expect( + sweepDurableWindowsPage(track.store, { + limit: 1, + clock: { + now: () => { + throw new Error("clock unavailable"); + }, + }, + }), + ).rejects.toThrow("clock"); + await expect( + sweepDurableWindowsPage(track.store, { + limit: 1, + clock, + maxClockSkewMs: -1, + }), + ).rejects.toThrow("maxClockSkewMs"); + expect(track.scans).toEqual([]); + }); +}); diff --git a/packages/rate-limit/src/durable.ts b/packages/rate-limit/src/durable.ts index f637562..0210f2a 100644 --- a/packages/rate-limit/src/durable.ts +++ b/packages/rate-limit/src/durable.ts @@ -2,6 +2,7 @@ import { systemClock } from "@pegma/spine"; import type { IsoTimestamp } from "@pegma/spine"; import { defineCollection, + MAX_SCAN_PAGE_SIZE, type Store, type StoredValue, } from "@pegma/storage-core"; @@ -182,7 +183,7 @@ function windowMatches( function descriptorMatches( value: StoredRateLimitRecord, expected: PartitionIdentity, - policy: RateLimitPolicy, + policy: Pick, ): boolean { return ( value.kind === "policy" && @@ -495,6 +496,114 @@ export function createDurableLimiter( }; } +export interface DurableWindowsSweepOptions extends LimiterOptions { + /** Physical rows per call, including descriptors and malformed/legacy rows. */ + readonly limit: number; + /** Persist and return the adapter's opaque continuation unchanged. */ + readonly cursor?: string; + /** Retention grace after each fixed window; defaults to 60 seconds. */ + readonly maxClockSkewMs?: number; +} + +export interface DurableWindowsSweepPage extends SweepResult { + readonly nextCursor: string | null; +} + +/** + * One global physical page, without policy filters or partition enumeration. + * + * Makes one scan, at most `limit` descriptor reads and at most `limit` + * version-conditional deletes. Only new-format windows whose decoded identity + * matches the actual scan key and current policy descriptor can be removed. + * Unknown legacy formats, malformed rows and descriptors are retained. + * + * Storage/time failures reject: callers must not advance their saved cursor on + * failure. Pages are not snapshots; repeat complete cycles for ongoing hygiene. + */ +export async function sweepDurableWindowsPage( + store: Store, + options: DurableWindowsSweepOptions, +): Promise { + const limit = options.limit; + const cursor = options.cursor; + if ( + !Number.isSafeInteger(limit) || + limit <= 0 || + limit > MAX_SCAN_PAGE_SIZE + ) { + throw new TypeError( + "Sweep limit must be a positive bounded scan page size.", + ); + } + if ( + cursor !== undefined && + (typeof cursor !== "string" || cursor.length === 0) + ) { + throw new TypeError("Sweep cursor must be an opaque nonempty string."); + } + const maxClockSkewMs = assertMaxClockSkewMs( + options.maxClockSkewMs ?? DEFAULT_MAX_CLOCK_SKEW_MS, + ); + const now = timeInMilliseconds(options.clock ?? systemClock, undefined); + if (now === null) + throw new TypeError("Sweep clock must return a canonical timestamp."); + const collection = store.collection(records); + const page = await collection.scan({ + limit, + ...(cursor === undefined ? {} : { cursor }), + }); + // Validate the physical envelope before examining any candidate or making + // keyed reads/deletes. Filtering first would hide an oversized physical page. + if ( + !Array.isArray(page.records) || + page.records.length > limit || + (page.nextCursor !== null && + (typeof page.nextCursor !== "string" || page.nextCursor.length === 0)) + ) { + throw new TypeError("Store returned an invalid bounded scan page."); + } + const nextCursor = page.nextCursor; + const rows = page.records.map((row) => ({ + key: { partition: row.key.partition, id: row.key.id }, + version: row.version, + value: { ...row.value }, + })); + let deleted = 0; + for (const row of rows) { + if (row.value === null || typeof row.value !== "object") continue; + const window = validWindow(row.value); + if ( + window === null || + window.count > window.limit || + window.partition !== `policy-${window.policyHash}` || + window.id !== idFor(window.windowStartMs, window.subjectHash) || + window.windowStartMs % window.windowMs !== 0 || + row.key.partition !== window.partition || + row.key.id !== window.id || + typeof row.version !== "string" || + row.version.length === 0 + ) + continue; + const expiresAt = window.windowStartMs + window.windowMs + maxClockSkewMs; + if (!Number.isSafeInteger(expiresAt) || expiresAt > now) continue; + const descriptor = await collection.getVersioned({ + partition: row.key.partition, + id: POLICY_DESCRIPTOR_ID, + }); + if ( + descriptor === null || + !descriptorMatches( + descriptor.value, + { partition: window.partition, policyHash: window.policyHash }, + window, + ) + ) + continue; + if (await collection.deleteIfUnchanged(row.key, row.version)) deleted += 1; + } + return { scanned: rows.length, deleted, nextCursor }; +} + export type { LimiterOptions, RateLimitDecision, diff --git a/packages/rate-limit/src/index.ts b/packages/rate-limit/src/index.ts index 1007388..ca25b0e 100644 --- a/packages/rate-limit/src/index.ts +++ b/packages/rate-limit/src/index.ts @@ -8,7 +8,10 @@ export { export { createMemoryLimiter } from "./memory.js"; export { createDurableLimiter, + sweepDurableWindowsPage, type DurableLimiterOptions, type DurableRateLimiter, type SweepResult, + type DurableWindowsSweepOptions, + type DurableWindowsSweepPage, } from "./durable.js"; From d8bb1ffc7141f4da77f4c3e941f44deb3fcdf6ae Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sun, 8 Nov 2026 11:04:35 -0500 Subject: [PATCH 2/3] Pin per-page work bounds and clarify cleanup failure semantics --- README.md | 10 ++++++- docs/PROJECT_PLAN.md | 7 +++++ packages/rate-limit/README.md | 20 +++++++++----- .../rate-limit/src/durable-sweep-page.test.ts | 26 +++++++++++++++++++ packages/rate-limit/src/durable.ts | 1 - 5 files changed, 56 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 9e3a6f5..a2401ac 100644 --- a/README.md +++ b/README.md @@ -72,10 +72,18 @@ It validates the page bound before filtering or keyed work, then makes at most new-format expired window whose identity matches its actual scan key, current policy descriptor, and unchanged opaque version can be deleted. Descriptors, legacy `0.2.0` rows, malformed rows, and policy mismatches remain stored. +Malformed stored payloads are distinct from invalid adapter page/row envelopes: +invalid envelopes and storage failures reject the call without skipping ahead. + +Descriptor reads and deletes run sequentially. The row/call bounds provide no +wall-clock or deadline guarantee. Choose a small page limit that fits the real +provider's storage latency, execution-time and subrequest budgets. The host persists the returned cursor unchanged after a successful page, including a page that deletes nothing. On rejection it retains the previous -cursor and retries later; no completed page is reported. Pages are not +cursor and retries later; no completed page is reported. A mid-page failure +does not roll back earlier conditional deletions, and retrying from the prior +cursor can repeat work. Pages are not snapshots, so repeat complete cycles. The helper applies its configured clock-skew grace across the page, 60 seconds by default; choose a common grace consistent with the host's peer-clock envelope. The helper itself leaves the diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index e2d0e3c..2d2bd11 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -194,11 +194,16 @@ storage. TypeScript, vitest, the ecosystem's standard layout. bounded by the required `limit`, with at most that many fresh descriptor reads and version-conditional deletes. Every returned row counts before filtering; there is no policy enumeration or unbounded list behind the page API. +Reads and deletes are sequential; these bounds do not guarantee wall-clock +completion or a deadline. Hosts choose a small page limit that fits the real +provider's storage latency, execution-time and subrequest budgets. Only structurally valid new-format expired windows whose identity matches the actual scan key and current immutable descriptor are deletion candidates. The exact captured window version must still match. Descriptors, legacy `0.2.0` layouts, malformed rows, and unknown/mismatched policy state remain. +Malformed stored payloads are retained; invalid adapter page/row envelopes and +storage failures reject rather than skip/advance. Grace defaults to 60 seconds and is explicit host configuration across the global pass. Adding this helper leaves the already-merged memory-tier and existing `allow()`/per-policy sweep behavior unchanged. @@ -206,6 +211,8 @@ existing `allow()`/per-policy sweep behavior unchanged. Hosts own cursor retention and scheduling. Preserve the opaque continuation after each successful page, including no-deletion pages; retain the previous cursor after an error. Pages are not snapshots, so repeat full cycles. The +earlier conditional deletions from a failed page are not rolled back; +retrying from the previous cursor can repeat work. The [source API](../packages/rate-limit/src/durable.ts) and [package contract](../packages/rate-limit/README.md#bounded-global-cleanup) define the interface; current-head gates, review, exact publication, and host diff --git a/packages/rate-limit/README.md b/packages/rate-limit/README.md index a0e1c1f..c90a67f 100644 --- a/packages/rate-limit/README.md +++ b/packages/rate-limit/README.md @@ -142,10 +142,15 @@ This is a source API signature, not an execution example or publication receipt. One call scans one global physical page of `rate-limit-windows`, without a policy filter, partition enumeration, `list`, or `listVersioned`. `scanned` counts every adapter-returned row before filtering, even descriptors, unknown -legacy layouts, malformed rows, and policies the current host no longer -constructs. An oversized/invalid physical page rejects before descriptor reads -or deletes. There are at most `limit` fresh descriptor reads and `limit` -`deleteIfUnchanged` calls. +legacy layouts, malformed stored payloads, and policies the current host no +longer constructs. A nonconforming adapter page/row envelope rejects instead +of being treated as a malformed stored payload to skip. Physical page +validation runs before descriptor reads or deletes. There are at most `limit` +fresh descriptor reads and `limit` `deleteIfUnchanged` calls. + +Those calls run sequentially. These are row/call bounds, with no wall-clock or +deadline guarantee. Hosts should choose a small page limit using the real +provider's storage latency, execution-time and subrequest budgets. Deletion requires a structurally valid new-format `window` with valid hashes, canonical window ID, aligned start, count within its stored limit, and a safe @@ -165,8 +170,11 @@ retained. Persist `nextCursor` unchanged only after success, including pages with no deletions. Null ends that cycle; it does not prove no concurrent/new rows exist. -Repeat complete cycles for ongoing hygiene. Storage or time failures reject -without a completed page or new cursor; retain the previous cursor on failure. +Repeat complete cycles for ongoing hygiene. Invalid adapter envelopes and +storage or time failures reject without a completed page or new cursor; +retain the previous cursor on failure. A mid-page failure does not roll back +conditional deletions that already succeeded. Retrying from the prior cursor +can repeat reads and deletion attempts. The helper itself does not change the already-merged memory behavior, `allow()` admission, or the existing per-policy sweep. diff --git a/packages/rate-limit/src/durable-sweep-page.test.ts b/packages/rate-limit/src/durable-sweep-page.test.ts index c137f20..0b8d45e 100644 --- a/packages/rate-limit/src/durable-sweep-page.test.ts +++ b/packages/rate-limit/src/durable-sweep-page.test.ts @@ -182,11 +182,19 @@ describe.each(stores)( let noMatchContinuation = false; let completed = false; for (let page = 0; page < 100; page += 1) { + const prior = { + scans: track.scans.length, + gets: track.gets(), + deletes: track.deletes(), + }; const result = await sweepDurableWindowsPage(track.store, { limit: 1, clock, ...(cursor === undefined ? {} : { cursor }), }); + expect(track.scans.slice(prior.scans)).toEqual([1]); + expect(track.gets() - prior.gets).toBeLessThanOrEqual(1); + expect(track.deletes() - prior.deletes).toBeLessThanOrEqual(1); expect(result.scanned).toBeLessThanOrEqual(1); scanned += result.scanned; deleted += result.deleted; @@ -393,6 +401,24 @@ describe.each(stores)( ); describe("bounded cleanup input failures", () => { + const invalidCursors: readonly unknown[] = ["", null, 0, true, {}, []]; + it.each(invalidCursors)( + "rejects invalid cursor %j before any storage I/O", + async (cursor) => { + const track = observed(createMemoryStore()); + await expect( + sweepDurableWindowsPage(track.store, { + limit: 1, + clock, + // JavaScript callers can bypass the declared string cursor type. + cursor: cursor as string, + }), + ).rejects.toThrow("cursor"); + expect(track.scans).toEqual([]); + expect(track.gets()).toBe(0); + expect(track.deletes()).toBe(0); + }, + ); it.each([0, -1, 1.5, 1001, Number.NaN, Number.POSITIVE_INFINITY])( "rejects invalid physical limit %s before scanning", async (limit) => { diff --git a/packages/rate-limit/src/durable.ts b/packages/rate-limit/src/durable.ts index 0210f2a..b0cffa4 100644 --- a/packages/rate-limit/src/durable.ts +++ b/packages/rate-limit/src/durable.ts @@ -570,7 +570,6 @@ export async function sweepDurableWindowsPage( })); let deleted = 0; for (const row of rows) { - if (row.value === null || typeof row.value !== "object") continue; const window = validWindow(row.value); if ( window === null || From 9e852b47d30d6089352a6d3e06d389e4ee9865f7 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sun, 8 Nov 2026 11:09:43 -0500 Subject: [PATCH 3/3] Reject invalid adapter envelopes before cleanup advances --- .../rate-limit/src/durable-sweep-page.test.ts | 76 ++++++++++++++++++- packages/rate-limit/src/durable.ts | 40 ++++++++-- 2 files changed, 104 insertions(+), 12 deletions(-) diff --git a/packages/rate-limit/src/durable-sweep-page.test.ts b/packages/rate-limit/src/durable-sweep-page.test.ts index 0b8d45e..22bf769 100644 --- a/packages/rate-limit/src/durable-sweep-page.test.ts +++ b/packages/rate-limit/src/durable-sweep-page.test.ts @@ -93,6 +93,8 @@ function field(value: StoredRecord, name: string): number { interface Hooks { readonly oversized?: boolean; readonly fail?: "scan" | "descriptor" | "delete"; + readonly corruptScanRow?: (row: ScanRecord) => unknown; + readonly descriptorValue?: () => unknown; readonly beforeDelete?: (key: EntityKey) => Promise; readonly afterDelete?: () => Promise; } @@ -108,17 +110,34 @@ function observed(inner: Store, hooks: Hooks = {}) { async scan(options) { scans.push(options.limit); if (hooks.fail === "scan") throw new Error("scan unavailable"); - return collection.scan( + const page = await collection.scan( hooks.oversized ? { ...options, limit: options.limit + 1 } : options, ); + const corrupt = hooks.corruptScanRow; + if (corrupt === undefined) return page; + return { + ...page, + // Violate only the returned adapter contract, after reading real + // rows. The last row pins validation before any earlier candidate. + records: page.records.map((row, index) => + index === page.records.length - 1 + ? (corrupt(row) as ScanRecord) + : row, + ), + }; }, async getVersioned(key) { gets += 1; if (hooks.fail === "descriptor") throw new Error("descriptor unavailable"); - return collection.getVersioned(key); + const descriptor = await collection.getVersioned(key); + if (descriptor === null || hooks.descriptorValue === undefined) + return descriptor; + // The physical descriptor and version are real; only its response + // value is deliberately outside the adapter's declared contract. + return { ...descriptor, value: hooks.descriptorValue() as T }; }, async deleteIfUnchanged(key, version) { deletes += 1; @@ -232,6 +251,55 @@ describe.each(stores)( expect(await rows(backing)).toHaveLength(2); }); + const invalidRows: ReadonlyArray< + readonly [string, (row: ScanRecord) => unknown] + > = [ + ["null row", () => null], + ["null key", (row) => ({ ...row, key: null })], + [ + "nonstring partition", + (row) => ({ ...row, key: { ...row.key, partition: 0 } }), + ], + ["nonstring id", (row) => ({ ...row, key: { ...row.key, id: 0 } })], + ["empty version", (row) => ({ ...row, version: "" })], + ["null value", (row) => ({ ...row, value: null })], + ["array value", (row) => ({ ...row, value: [] })], + ["primitive value", (row) => ({ ...row, value: 0 })], + ]; + it.each(invalidRows)( + "rejects a final %s envelope before any descriptor read or delete", + async (_label, corruptScanRow) => { + const backing = makeStore(); + await seed(backing, "invalid-row-envelope"); + const before = await rows(backing); + const track = observed(backing, { corruptScanRow }); + await expect( + sweepDurableWindowsPage(track.store, { limit: 100, clock }), + ).rejects.toThrow("scan row envelope"); + expect(track.scans).toEqual([100]); + expect(track.gets()).toBe(0); + expect(track.deletes()).toBe(0); + expect(await rows(backing)).toEqual(before); + }, + ); + + it.each([null, [], 0].map((value) => ({ value })))( + "rejects an invalid descriptor value %j without deleting its real expired candidate", + async ({ value }) => { + const backing = makeStore(); + await seed(backing, "invalid-descriptor-envelope"); + const before = await rows(backing); + const track = observed(backing, { descriptorValue: () => value }); + await expect( + sweepDurableWindowsPage(track.store, { limit: 100, clock }), + ).rejects.toThrow("descriptor envelope"); + expect(track.scans).toEqual([100]); + expect(track.gets()).toBe(1); + expect(track.deletes()).toBe(0); + expect(await rows(backing)).toEqual(before); + }, + ); + it("retains malformed/new-format identities and never pairs a payload key with another row's version", async () => { const backing = makeStore(); await seed(backing, "malformed-windows", [ @@ -402,9 +470,9 @@ describe.each(stores)( describe("bounded cleanup input failures", () => { const invalidCursors: readonly unknown[] = ["", null, 0, true, {}, []]; - it.each(invalidCursors)( + it.each(invalidCursors.map((cursor) => ({ cursor })))( "rejects invalid cursor %j before any storage I/O", - async (cursor) => { + async ({ cursor }) => { const track = observed(createMemoryStore()); await expect( sweepDurableWindowsPage(track.store, { diff --git a/packages/rate-limit/src/durable.ts b/packages/rate-limit/src/durable.ts index b0cffa4..5e182e3 100644 --- a/packages/rate-limit/src/durable.ts +++ b/packages/rate-limit/src/durable.ts @@ -563,11 +563,28 @@ export async function sweepDurableWindowsPage( throw new TypeError("Store returned an invalid bounded scan page."); } const nextCursor = page.nextCursor; - const rows = page.records.map((row) => ({ - key: { partition: row.key.partition, id: row.key.id }, - version: row.version, - value: { ...row.value }, - })); + const rows = page.records.map((row) => { + if ( + row === null || + typeof row !== "object" || + row.key === null || + typeof row.key !== "object" || + typeof row.key.partition !== "string" || + typeof row.key.id !== "string" || + typeof row.version !== "string" || + row.version.length === 0 || + row.value === null || + typeof row.value !== "object" || + Array.isArray(row.value) + ) { + throw new TypeError("Store returned an invalid scan row envelope."); + } + return { + key: { partition: row.key.partition, id: row.key.id }, + version: row.version, + value: { ...row.value }, + }; + }); let deleted = 0; for (const row of rows) { const window = validWindow(row.value); @@ -578,9 +595,7 @@ export async function sweepDurableWindowsPage( window.id !== idFor(window.windowStartMs, window.subjectHash) || window.windowStartMs % window.windowMs !== 0 || row.key.partition !== window.partition || - row.key.id !== window.id || - typeof row.version !== "string" || - row.version.length === 0 + row.key.id !== window.id ) continue; const expiresAt = window.windowStartMs + window.windowMs + maxClockSkewMs; @@ -589,6 +604,15 @@ export async function sweepDurableWindowsPage( partition: row.key.partition, id: POLICY_DESCRIPTOR_ID, }); + if ( + descriptor !== null && + (typeof descriptor !== "object" || + descriptor.value === null || + typeof descriptor.value !== "object" || + Array.isArray(descriptor.value)) + ) { + throw new TypeError("Store returned an invalid descriptor envelope."); + } if ( descriptor === null || !descriptorMatches(