Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): replace KV TTL-based throttle with timestamp-based throttle
Genere87808689394
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsindex 8270805db..d8cfd3913 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts@@ -14,7 +14,7 @@ import { log } from "@/lib/logger";export const POST = withAuth(async (req: NextRequest, ctx) => {const { env } = getCloudflareContext();const db = getDb((env as Env).DB);- const { cached, cachedBatch, cacheKeys } = await import("@/lib/cache");+ const { cached, cachedBatch, cacheKeys, throttled } = await import("@/lib/cache");const [body, err] = await parseBody(req, PollRequestSchema);if (err) return err;@@ -34,21 +34,20 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeJSON({ tasks: [], evicted: true });}- // 2. Liveness: write heartbeat to KV (fast) + D1 upsert throttled to stay under OFFLINE_THRESHOLD- // KV is eventually consistent across colos, so D1 must stay fresh enough as fallback.- // Derived from timing constants so it auto-adapts if threshold or poll interval changes.+ // 2. Liveness: write heartbeat to KV (fast) + D1 upsert throttled via timestamp.+ // KV heartbeat is the primary source; D1 is the cross-colo fallback.+ // Uses timestamp-based throttle (not KV TTL) so the interval can be < 60s.const D1_HEARTBEAT_THROTTLE_S = Math.floor((OFFLINE_THRESHOLD_MS - POLL_INTERVAL_MS) / 1000) - 1;- // Non-critical — D1 transient failures should not block task pollingconst kv = (env as Env).CACHE_KV ?? null;if (kv) {kv.put(cacheKeys.heartbeat(ctx.workspaceId, body.daemon_id),new Date().toISOString(),- { expirationTtl: 15 },+ { expirationTtl: 60 },).catch(() => {});}try {- await cached(+ await throttled(`hb_d1:${ctx.workspaceId}:${body.daemon_id}`,D1_HEARTBEAT_THROTTLE_S,async () => {@@ -57,7 +56,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {workspaceId: ctx.workspaceId!,deviceInfo: body.daemon_id,});- return "1";},);} catch (e) {@@ -80,20 +78,15 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// 3b. Promote due calendar events — throttled to once per 30s per workspacetry {- let calRun = false;- await cached(`cal:${ctx.workspaceId}`, 30, async () => {- calRun = true;- return "1";- }).catch(() => { calRun = true; });- if (calRun) {+ await throttled(`cal:${ctx.workspaceId}`, 30, async () => {const enqueued = await promoteDueCalendarEventsForWorkspace(db,- ctx.workspaceId,+ ctx.workspaceId!,);if (enqueued > 0) {log.info("calendar: enqueued", { workspaceId: ctx.workspaceId, enqueued });}- }+ });} catch (err) {log.warn("calendar: promote failed", {workspaceId: ctx.workspaceId,@@ -268,7 +261,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const miscKey = `misc:${ctx.workspaceId}:${body.daemon_id}`;let runMisc = false;try {- await cached(miscKey, 30, async () => { runMisc = true; return "1"; });+ runMisc = await throttled(miscKey, 30, async () => {});} catch { runMisc = true; }if (runMisc) {@@ -344,11 +337,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// File browse requests — expireStale throttled to 5s, but check pending every polllet fileRequests: FileRequestItem[] | undefined;try {- let expireRun = false;- await cached(`expire_fr:${ctx.workspaceId}`, 5, async () => { expireRun = true; return "1"; }).catch(() => { expireRun = true; });- if (expireRun) {- await queries.workspaceFileRequest.expireStale(db, ctx.workspaceId);- }+ await throttled(`expire_fr:${ctx.workspaceId}`, 5, async () => {+ await queries.workspaceFileRequest.expireStale(db, ctx.workspaceId!);+ });const pending = await queries.workspaceFileRequest.getPendingByWorkspace(db, ctx.workspaceId);if (pending.length > 0) {fileRequests = pending.map((r) => ({diff --git a/src/web/src/lib/cache.test.ts b/src/web/src/lib/cache.test.tsindex 2c74c9a9a..f342c73e7 100644--- a/src/web/src/lib/cache.test.ts+++ b/src/web/src/lib/cache.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from "vitest";-import { cached, cachedBatch, invalidate, invalidateMany, bindCacheKV, cacheKeys, getKV } from "./cache";+import { cached, cachedBatch, invalidate, invalidateMany, bindCacheKV, cacheKeys, getKV, throttled } from "./cache";function createMockKV() {const store = new Map<string, { value: string; expiration?: number }>();@@ -79,6 +79,18 @@ describe("cache", () => {warnSpy.mockRestore();});+ it("clamps TTL to minimum 60s for KV write", async () => {+ const fn = vi.fn(async () => "val");++ await cached("ttl-key", 5, fn);++ expect(mockKV.put).toHaveBeenCalledWith(+ "ttl-key",+ JSON.stringify("val"),+ { expirationTtl: 60 },+ );+ });+it("does not store null values to KV", async () => {const fn = vi.fn(async () => null);@@ -224,6 +236,52 @@ describe("cache", () => {});});+ describe("throttled()", () => {+ it("runs fn on first call (no prior timestamp)", async () => {+ const fn = vi.fn(async () => {});+ const ran = await throttled("thr-key", 5, fn);+ expect(ran).toBe(true);+ expect(fn).toHaveBeenCalledOnce();+ expect(mockKV.put).toHaveBeenCalledWith(+ "thr-key",+ expect.stringMatching(/^\d+$/),+ { expirationTtl: 60 },+ );+ });++ it("skips fn when within throttle interval", async () => {+ mockKV._store.set("thr-key", { value: String(Date.now()) });+ const fn = vi.fn(async () => {});+ const ran = await throttled("thr-key", 5, fn);+ expect(ran).toBe(false);+ expect(fn).not.toHaveBeenCalled();+ });++ it("runs fn when throttle interval has elapsed", async () => {+ mockKV._store.set("thr-key", { value: String(Date.now() - 6000) });+ const fn = vi.fn(async () => {});+ const ran = await throttled("thr-key", 5, fn);+ expect(ran).toBe(true);+ expect(fn).toHaveBeenCalledOnce();+ });++ it("runs fn when KV is not bound", async () => {+ bindCacheKV(null);+ const fn = vi.fn(async () => {});+ const ran = await throttled("thr-key", 5, fn);+ expect(ran).toBe(true);+ expect(fn).toHaveBeenCalledOnce();+ });++ it("runs fn when KV read fails", async () => {+ (mockKV.get as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("KV down"));+ const fn = vi.fn(async () => {});+ const ran = await throttled("thr-key", 5, fn);+ expect(ran).toBe(true);+ expect(fn).toHaveBeenCalledOnce();+ });+ });+describe("KV complete failure scenario", () => {it("all operations gracefully degrade when KV is entirely down", async () => {const brokenKV = {diff --git a/src/web/src/lib/cache.ts b/src/web/src/lib/cache.tsindex 1cd634941..27d2b3a65 100644--- a/src/web/src/lib/cache.ts+++ b/src/web/src/lib/cache.ts@@ -8,6 +8,8 @@ export function getKV(): KVNamespace | null {return _kv ?? null;}+const MIN_KV_TTL = 60;+export async function cached<T>(key: string,ttlSeconds: number,@@ -26,7 +28,7 @@ export async function cached<T>(const value = await fn();if (value != null && kv) {- kv.put(key, JSON.stringify(value), { expirationTtl: ttlSeconds }).catch((err) => {+ kv.put(key, JSON.stringify(value), { expirationTtl: Math.max(ttlSeconds, MIN_KV_TTL) }).catch((err) => {console.warn(`[cache] KV write failed for ${key}:`, err);});}@@ -73,7 +75,7 @@ export async function cachedBatch<T>(for (const [key, value] of fetched) {result.set(key, value);if (value != null && kv) {- kv.put(key, JSON.stringify(value), { expirationTtl: ttlSeconds }).catch((err) => {+ kv.put(key, JSON.stringify(value), { expirationTtl: Math.max(ttlSeconds, MIN_KV_TTL) }).catch((err) => {console.warn(`[cache] KV batch write failed for ${key}:`, err);});}@@ -83,6 +85,38 @@ export async function cachedBatch<T>(return result;}+/**+ * Timestamp-based throttle — not limited by KV's 60s minimum TTL.+ * Stores last-run timestamp in KV; skips `fn` if within `intervalSeconds`.+ * Returns true if `fn` ran, false if throttled.+ */+export async function throttled(+ key: string,+ intervalSeconds: number,+ fn: () => Promise<void>,+): Promise<boolean> {+ const kv = getKV();+ if (kv) {+ try {+ const raw = await kv.get(key);+ if (raw) {+ const elapsed = Date.now() - parseInt(raw, 10);+ if (elapsed < intervalSeconds * 1000) return false;+ }+ } catch {}+ }++ await fn();++ if (kv) {+ kv.put(key, String(Date.now()), {+ expirationTtl: Math.max(intervalSeconds * 10, MIN_KV_TTL),+ }).catch(() => {});+ }++ return true;+}+export async function invalidate(key: string): Promise<void> {const kv = getKV();if (kv) await kv.delete(key).catch((err) => {diff --git a/src/web/src/lib/services/sweep.ts b/src/web/src/lib/services/sweep.tsindex af1b0224d..43c889ee0 100644--- a/src/web/src/lib/services/sweep.ts+++ b/src/web/src/lib/services/sweep.ts@@ -1,7 +1,7 @@import type { Database } from "@alook/shared";import { queries } from "@alook/shared";import { TaskService } from "./task";-import { cached } from "@/lib/cache";+import { throttled } from "@/lib/cache";const SWEEP_INTERVAL_S = 30;@@ -11,20 +11,17 @@ export function _resetSweepThrottle() {}/*** Unified workspace housekeeping. Any code path that wants to ensure* stale state is cleaned up just calls this one function.- * Rate-limited to once per 30s per workspace via KV.+ * Rate-limited to once per 30s per workspace via KV (timestamp-based).*/export async function sweepStaleState(db: Database, workspaceId: string) {const lockKey = `sweep:${workspaceId}`;- let locked = false;+ let shouldRun = false;try {- await cached<string>(lockKey, SWEEP_INTERVAL_S, async () => {- locked = true;- return new Date().toISOString();- });- if (!locked) return;+ shouldRun = await throttled(lockKey, SWEEP_INTERVAL_S, async () => {});} catch {- locked = true;+ shouldRun = true;}+ if (!shouldRun) return;// 1. Fail tasks stuck in "dispatched" for >20s (daemon crashed between claim and start)const staleDispatched = await queries.task.failStaleDispatchedTasks(db, workspaceId);