TypeScript
fix(infra): keep task cache cleanup ahead of uploads (#25143)
Julius Marminge2ee1529504e6
diff --git a/infra/task-cache/README.md b/infra/task-cache/README.mdindex da740db1059..5662058b93b 100644--- a/infra/task-cache/README.md+++ b/infra/task-cache/README.md@@ -60,7 +60,7 @@ The smoke check uploads a unique fixture, restores its output into a cold second- Vite Task separates operating systems and CPU architectures. macOS results do not satisfy Linux CI; Linux developer machines can populate compatible CI results.- The current protocol retains one result for each execution key. Competing source versions can overwrite each other's entry. Inputs are validated before reuse, so this causes misses rather than stale hits. Merging to main does not promote or reset the cache.- A local hit makes no remote request and is not uploaded retroactively. Clear only an isolated worktree's task cache when testing uploads of an already-cached task.-- Production retains results for seven days within an 8 GB budget. Remote errors fall back to execution. `VP_REMOTE_CACHE=off vp run ...` disables the remote tier for one invocation.+- Production retains results for seven days within a 64 GB budget. Remote errors fall back to execution. `VP_REMOTE_CACHE=off vp run ...` disables the remote tier for one invocation.## Savings and tracingdiff --git a/infra/task-cache/src/Cleanup.test.ts b/infra/task-cache/src/Cleanup.test.tsnew file mode 100644index 00000000000..b68cba81be7--- /dev/null+++ b/infra/task-cache/src/Cleanup.test.ts@@ -0,0 +1,112 @@+// @effect-diagnostics nodeBuiltinImport:off - real SQLite exercises concurrent D1 claims and accounting.+import * as NodeFS from "node:fs";+import * as NodeSqlite from "node:sqlite";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import { expect, it } from "@effect/vitest";+import { cleanup } from "../vendor/vite-plus-remote-cache-cloudflare/src/database.ts";+import * as Cache from "./Cache.ts";+import * as Cleanup from "./Cleanup.ts";++it.effect("cleans three full disjoint batches within the D1 invocation budget", () =>+ Effect.gen(function* () {+ const sqlite = new NodeSqlite.DatabaseSync(":memory:");+ try {+ sqlite.exec(+ NodeFS.readFileSync(+ new URL(+ "../vendor/vite-plus-remote-cache-cloudflare/migrations/0001_cache.sql",+ import.meta.url,+ ),+ "utf8",+ ),+ );+ sqlite.exec(`+ INSERT INTO scopes (scope_id, endpoint, repository, repository_id, repository_owner_id, branch)+ VALUES ('fixture', 'https://cache.example', 'owner/repo', '1', '2', 'refs/heads/main');+ WITH RECURSIVE ids(id) AS (SELECT 0 UNION ALL SELECT id+1 FROM ids WHERE id<1023)+ INSERT INTO generations (generation_id, scope_id, state, policy_version, token_exp,+ lease_until, gc_after, value_object, blob_object, charged_bytes)+ SELECT 'g'||id, 'fixture', 'retired', 1, unixepoch()+3600, 0, 0,+ 'value/'||id, 'blob/'||id, 1 FROM ids;+ INSERT INTO generations (generation_id, scope_id, state, policy_version, token_exp,+ lease_until, gc_after, value_object, blob_object, charged_bytes)+ VALUES ('live', 'fixture', 'ready', 1, unixepoch()+3600, 0, unixepoch()+3600,+ 'live/value', 'live/blob', 1);+ `);+ let queries = 0;+ const claims: string[][] = [];+ const deleted = new Set<string>();+ const query = () => {+ if (++queries > 1000) throw new Error("D1 query budget exceeded");+ };+ const prepare = (sql: string) => {+ let args: NodeSqlite.SQLInputValue[] = [];+ const statement = {+ bind: (...values: NodeSqlite.SQLInputValue[]) => {+ args = values.map((value) =>+ value instanceof ArrayBuffer ? new Uint8Array(value) : value,+ );+ return statement;+ },+ all: async () => {+ query();+ const results = sqlite.prepare(sql).all(...args);+ if (sql.startsWith("UPDATE generations"))+ claims.push(results.map((row) => String(row.generation_id)));+ return { results };+ },+ run: async () => {+ query();+ if (sql.startsWith("DELETE FROM generations")) {+ const row = sqlite+ .prepare(+ "SELECT value_object, blob_object FROM generations WHERE generation_id = ?",+ )+ .get(args[0]!);+ expect(deleted.has(String(row!.value_object))).toBe(true);+ expect(deleted.has(String(row!.blob_object))).toBe(true);+ }+ return sqlite.prepare(sql).run(...args);+ },+ };+ return statement;+ };+ const env = {+ GC_BATCH_SIZE: String(Cleanup.batchSize),+ INDEX: {+ prepare,+ batch: async (statements: ReturnType<typeof prepare>[]) =>+ Promise.all(statements.map((statement) => statement.run())),+ },+ ARTIFACTS: {+ delete: async (keys: string[]) => {+ for (const key of keys) {+ expect(deleted.has(key)).toBe(false);+ deleted.add(key);+ }+ },+ },+ } as unknown as Parameters<typeof cleanup>[0];+ yield* Cleanup.run().pipe(+ Effect.provide(+ Layer.succeed(Cache.Cache, {+ handle: () => Effect.die("unused"),+ cleanup: Effect.promise(() => cleanup(env)),+ }),+ ),+ );+ expect(claims.map((claim) => claim.length)).toEqual([256, 256, 256]);+ expect(new Set(claims.flat()).size).toBe(768);+ expect(queries).toBeLessThanOrEqual(1000);+ expect(deleted.size).toBe(1536);+ expect(deleted.has("live/value")).toBe(false);+ expect(sqlite.prepare("SELECT charged_bytes FROM scopes").get()).toEqual({+ charged_bytes: 257,+ });+ expect(sqlite.prepare("SELECT count(*) AS n FROM generations").get()).toEqual({ n: 257 });+ } finally {+ sqlite.close();+ }+ }),+);diff --git a/infra/task-cache/src/Cleanup.ts b/infra/task-cache/src/Cleanup.tsnew file mode 100644index 00000000000..5d6e48ca036--- /dev/null+++ b/infra/task-cache/src/Cleanup.ts@@ -0,0 +1,13 @@+import * as Effect from "effect/Effect";+import * as Cache from "./Cache.ts";++export const batchSize = 256;++export const run = Effect.fn("TaskCache.cleanup")(function* () {+ const cache = yield* Cache.Cache;+ // Three full batches stay below D1’s 1,000-query invocation limit.+ yield* Effect.all([cache.cleanup, cache.cleanup, cache.cleanup], {+ concurrency: 3,+ discard: true,+ });+});diff --git a/infra/task-cache/src/worker.ts b/infra/task-cache/src/worker.tsindex b9b60c7f961..04a3f41643c 100644--- a/infra/task-cache/src/worker.ts+++ b/infra/task-cache/src/worker.ts@@ -8,6 +8,7 @@ import * as Redacted from "effect/Redacted";import * as HttpServerResponse from "effect/http/HttpServerResponse";import * as Admission from "./Admission.ts";import * as Cache from "./Cache.ts";+import * as Cleanup from "./Cleanup.ts";import * as NativeClients from "./NativeClients.ts";import * as Savings from "./Savings.ts";import type { ProtocolBindings } from "./protocolTypes.ts";@@ -42,7 +43,7 @@ export const layer = Worker.make(return Cache.Bindings.of({INDEX: yield* database.raw,ARTIFACTS: (yield* artifacts.raw) as unknown as ProtocolBindings["ARTIFACTS"],- GC_BATCH_SIZE: "16",+ GC_BATCH_SIZE: String(Cleanup.batchSize),developerKeys: Redacted.value(developerKeys),readerKeys: Redacted.value(readerKeys),readLimit: yield* reads.raw,@@ -76,12 +77,8 @@ export const layer = Worker.make(savingsLayer,]),);- yield* Cloudflare.Workers.cron("*/5 * * * *", () =>- Cache.Cache.pipe(- Effect.flatMap((cache) => cache.cleanup),- Effect.provide(runtime),- Effect.orDie,- ),+ yield* Cloudflare.Workers.cron("* * * * *", () =>+ Cleanup.run().pipe(Effect.provide(runtime), Effect.orDie),);yield* Cloudflare.Workers.cron("0 * * * *", () =>Savings.Savings.pipe(