From 65347feabe10f5ea6691e25eefb2c7e46f060f98 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 3 Nov 2026 02:34:51 -0600 Subject: [PATCH 1/2] fix(aggregator): short-TTL coalescing cache for /today fan-out (#1179) Warm /today?full=1 and /frag/today requests reuse the last successful read for 10s instead of re-fanning out to board, roadmap, attention, health/quota, and orchestration on every request; concurrent cold requests share one in-flight load. Provenance strings/detail stay live per request; only successful reads are cached. --- pm-stack/aggregator/src/server.ts | 24 +- pm-stack/aggregator/src/today-cache.ts | 74 ++++++ .../aggregator/test/today-cache-1179.test.ts | 236 ++++++++++++++++++ 3 files changed, 332 insertions(+), 2 deletions(-) create mode 100644 pm-stack/aggregator/src/today-cache.ts create mode 100644 pm-stack/aggregator/test/today-cache-1179.test.ts diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 88df1203df..7e66a9d068 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -138,6 +138,7 @@ import { liveSource } from "./sources/live.ts"; import { buildQueueView, queueInputsStale } from "./queue-view.ts"; import { dashboardResponseWithinDeadline } from "./assembly-deadline.ts"; import { dispatchStateFor, fetchRfaState, RFA_NOT_PICKED_UP } from "./sources/ready-for-agent.ts"; +import { TodayCache, TODAY_CACHE_TTL_MS } from "./today-cache.ts"; const cfg = loadConfig(); const commentsStore = new CommentsStore(cfg.commentsFile); @@ -736,7 +737,7 @@ async function attentionRender() { return { view, coverage, counts, act, briefs, census }; } -async function todaySignals() { +async function loadTodaySignals() { const [health, quotaResult] = await Promise.all([ healthContext(false).catch(() => null), source @@ -747,7 +748,17 @@ async function todaySignals() { return { health, quota: quotaResult.quota, quotaUnavailable: quotaResult.unavailable }; } -async function todayContext() { +// #1179: the shell (/today) and the fragment (/frag/today) both need +// the health+quota strip, seconds apart on every page view. Bound the +// repeated live reads with a short TTL; concurrent cold requests share +// the in-flight load. Provenance stays truthful: prov()/provDetail() +// are still read live per request at the call sites below. +const todaySignalsCache = new TodayCache>>(TODAY_CACHE_TTL_MS); +async function todaySignals(): Promise>> { + return todaySignalsCache.get(loadTodaySignals); +} + +async function loadTodayContext() { const [{ board, items }, { rows, pool }, { view, coverage, orchestration }, signals] = await Promise.all([ boardContext(), roadmapContext(), @@ -766,6 +777,15 @@ async function todayContext() { }; } +// #1179: /today?full=1, /frag/today, and /api/today.json all render +// from this one assembly. Same short-TTL + coalescing contract as the +// signals cache above; a throwing load is never cached (the fetch +// error boundary still 500s) and expiry triggers a fresh read. +const todayContextCache = new TodayCache>>(TODAY_CACHE_TTL_MS); +async function todayContext(): Promise>> { + return todayContextCache.get(loadTodayContext); +} + async function queueContext() { const [{ board, items }, pool, orchestration] = await Promise.all([ boardContext(), diff --git a/pm-stack/aggregator/src/today-cache.ts b/pm-stack/aggregator/src/today-cache.ts new file mode 100644 index 0000000000..c18b74a782 --- /dev/null +++ b/pm-stack/aggregator/src/today-cache.ts @@ -0,0 +1,74 @@ +// The /today short-TTL cache (#1179). +// +// todayContext() fans out to board, roadmap, attention, health/quota, +// and orchestration on EVERY /today?full=1 and /frag/today request, and +// the /today shell's /frag/today load means a single page view costs +// that fan-out twice in quick succession (shell signals + fragment). +// In live mode those are Kaneo/Grist/projector reads (~1.8s measured +// on #1179), so repeated warm refreshes and concurrent cold loads were +// all paying the full fan-out. +// +// This module bounds that repeated work: a small TTL (10s, inside the +// issue's proposed 5-15s window) serves warm hits from the last +// successful read, and concurrent cold requests share one in-flight +// load instead of each fanning out. +// +// Truthfulness notes (the freshness-sensitive part of #1179): +// - Only successful reads are cached, and only the DERIVED payload +// (board/roadmap/attention/health/quota views). The per-request +// provenance strings (source.provenance()) and detail +// (provenanceDetail(), with its feed-age computation) are still read +// live on every request in server.ts, so the provenance STATE +// (live/fixtures/stale/…) never reflects cache time. +// - Ages inside the cached payload (feed-age text, the orchestration +// section's generatedAt) are stamped at read time and can lag by at +// most the TTL — the same bound the health probe cache (60s, #1147) +// already accepts, at a 6x tighter budget. +// - Fail-soft fallbacks (empty quota view + quotaUnavailable, null +// health) are cached as-is: they ARE the honest degraded state of +// that read, and expiry (or a loader throw, which is never cached) +// triggers a fresh read on the next request. + +export const TODAY_CACHE_TTL_MS = 10_000; + +export class TodayCache { + private cached: { at: number; data: T } | null = null; + private inflight: Promise | null = null; + + constructor( + private readonly ttlMs: number = TODAY_CACHE_TTL_MS, + private readonly now: () => number = Date.now, + ) {} + + /** Forget the cached value and any shared in-flight load (tests). */ + clear(): void { + this.cached = null; + this.inflight = null; + } + + /** + * Return the cached value on a warm hit, the shared in-flight load + * when a cold load is already running, or run `loader` and cache a + * successful result. A throwing loader never poisons the cache: the + * in-flight slot is released and the error rethrows, so the next + * request retries (and server.ts's error boundary still 500s). + */ + get(loader: () => Promise): Promise { + const at = this.now(); + if (this.cached && at - this.cached.at < this.ttlMs) { + return Promise.resolve(this.cached.data); + } + this.inflight ??= loader().then( + (data) => { + this.cached = { at: this.now(), data }; + this.inflight = null; + return data; + }, + (err) => { + this.inflight = null; + throw err; + }, + ); + return this.inflight; + } +} diff --git a/pm-stack/aggregator/test/today-cache-1179.test.ts b/pm-stack/aggregator/test/today-cache-1179.test.ts new file mode 100644 index 0000000000..bb21685e03 --- /dev/null +++ b/pm-stack/aggregator/test/today-cache-1179.test.ts @@ -0,0 +1,236 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { spawn, type Subprocess } from "bun"; +import { mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { TODAY_CACHE_TTL_MS, TodayCache } from "../src/today-cache.ts"; + +// #1179: repeated warm /today + /frag/today requests must not repeat +// the live-source fan-out, and concurrent cold requests must share one +// in-flight load — while failures, provenance, and degraded state stay +// truthful. Unit coverage pins the cache contract; the route section +// below pins the wiring through a booted fixture-mode server. + +describe("TodayCache cold miss / warm hit / expiry", () => { + test("cold miss runs the loader and caches the result", async () => { + let now = 1_000_000; + let calls = 0; + const cache = new TodayCache(10_000, () => now); + const first = await cache.get(async () => { + calls++; + return "v1"; + }); + expect(first).toBe("v1"); + expect(calls).toBe(1); + // Warm hit: same value, loader not re-run. + const second = await cache.get(async () => { + calls++; + return "v2"; + }); + expect(second).toBe("v1"); + expect(calls).toBe(1); + }); + + test("expiry triggers a fresh read", async () => { + let now = 1_000_000; + let calls = 0; + const cache = new TodayCache(10_000, () => now); + await cache.get(async () => { + calls++; + return `v${calls}`; + }); + now += TODAY_CACHE_TTL_MS - 1; + expect(await cache.get(async () => "stale-never")).toBe("v1"); + expect(calls).toBe(1); + // Exactly at the TTL the entry is stale — a fresh read runs. + now += 1; + expect(await cache.get(async () => `v${++calls}`)).toBe("v2"); + expect(calls).toBe(2); + }); + + test("clear() forces the next read to miss", async () => { + let calls = 0; + const cache = new TodayCache(); + await cache.get(async () => `v${++calls}`); + cache.clear(); + expect(await cache.get(async () => `v${++calls}`)).toBe("v2"); + expect(calls).toBe(2); + }); +}); + +describe("TodayCache concurrent coalescing", () => { + test("concurrent cold requests share one in-flight load", async () => { + let calls = 0; + let release!: (v: string) => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const cache = new TodayCache(); + const loader = async () => { + calls++; + return gate; + }; + const pending = [cache.get(loader), cache.get(loader), cache.get(loader)]; + // Let all three attach to the in-flight load before it resolves. + await Bun.sleep(10); + expect(calls).toBe(1); + release("shared"); + const results = await Promise.all(pending); + expect(results).toEqual(["shared", "shared", "shared"]); + expect(calls).toBe(1); + // The coalesced result is now the warm value. + expect(await cache.get(async () => "never")).toBe("shared"); + expect(calls).toBe(1); + }); +}); + +describe("TodayCache failure and degraded-state behavior", () => { + test("a throwing loader never poisons the cache; the next request retries", async () => { + let calls = 0; + const cache = new TodayCache(); + await expect( + cache.get(async () => { + calls++; + throw new Error("kaneo unreachable"); + }), + ).rejects.toThrow("kaneo unreachable"); + expect(calls).toBe(1); + // Retry runs the loader again instead of serving the failure… + expect(await cache.get(async () => `recovered-${++calls}`)).toBe("recovered-2"); + expect(calls).toBe(2); + // …and the successful read is cached normally. + expect(await cache.get(async () => "never")).toBe("recovered-2"); + expect(calls).toBe(2); + }); + + test("concurrent waiters on a failed load all reject and release the slot", async () => { + let calls = 0; + let reject!: (e: Error) => void; + const gate = new Promise((_, rej) => { + reject = rej; + }); + const cache = new TodayCache(); + const loader = async () => { + calls++; + return gate; + }; + const pending = [cache.get(loader), cache.get(loader)]; + await Bun.sleep(10); + expect(calls).toBe(1); + reject(new Error("grist timeout")); + await expect(Promise.all(pending)).rejects.toThrow("grist timeout"); + expect( + await cache.get(async () => { + calls++; + return "fresh"; + }), + ).toBe("fresh"); + expect(calls).toBe(2); + }); + + test("fail-soft degraded values are served truthfully within the TTL, then refreshed", async () => { + // server.ts's loaders catch per-facet: a quota outage resolves to + // { quotaUnavailable: true }, which the cache must preserve as-is + // (not mask, not throw) until expiry triggers a fresh read. + let now = 1_000_000; + let outage = true; + const cache = new TodayCache<{ quotaUnavailable: boolean }>(10_000, () => now); + const loader = async () => ({ quotaUnavailable: outage }); + expect((await cache.get(loader)).quotaUnavailable).toBe(true); + outage = false; // the source recovers behind the cache + expect((await cache.get(loader)).quotaUnavailable).toBe(true); + now += TODAY_CACHE_TTL_MS; + expect((await cache.get(loader)).quotaUnavailable).toBe(false); + }); + + test("warm hits serve the last read's stamps, not fresh ones (bounded lag)", async () => { + // Provenance STATE stays live per request (server.ts reads + // prov()/provDetail() outside the cache); the cached payload keeps + // its read-time stamps, lagging by at most the TTL. + let now = 1_000_000; + const cache = new TodayCache<{ readAt: number }>(10_000, () => now); + const first = await cache.get(async () => ({ readAt: now })); + now += 5_000; + const second = await cache.get(async () => ({ readAt: now })); + expect(second).toBe(first); + expect(second.readAt).toBe(1_000_000); + }); +}); + +let proc: Subprocess | undefined; +let base = ""; + +beforeAll(async () => { + const dir = await mkdtemp(join(tmpdir(), "pm-today-cache-1179-")); + const port = 6000 + Math.floor(Math.random() * 800); + base = `http://127.0.0.1:${port}`; + proc = spawn({ + cmd: ["bun", "run", "src/server.ts"], + cwd: join(import.meta.dir, ".."), + env: { + ...Bun.env, + PM_AGG_PORT: String(port), + PM_AGG_FEED_FILE: join(dir, "no-feed.json"), + PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), + PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), + PM_AGG_ACTIONS_FILE: join(dir, "actions.json"), + PM_AGG_SNAPSHOTS_DIR: join(dir, "snapshots"), + PM_AGG_OPENCHAMBER_STATE: join(dir, "no-state.json"), + PM_AGG_QUOTA_VIEW: join(dir, "no-quota-view.md"), + PM_AGG_QUOTA_REGISTRY: join(dir, "no-quota-registry.md"), + PM_PROJECTOR_URL: "off", + KANEO_ADMIN_EMAIL: "", + KANEO_ADMIN_PASSWORD: "", + GRIST_API_KEY: "", + }, + stdout: "pipe", + stderr: "inherit", + }); + const deadline = Date.now() + 20_000; + let up = false; + while (Date.now() < deadline && !up) { + try { + const res = await fetch(`${base}/api/health`); + up = res.ok; + } catch { + /* not up yet */ + } + if (!up) await Bun.sleep(150); + } + expect(up).toBe(true); +}); + +afterAll(() => { + proc?.kill(); +}); + +describe("/today routes through the cache (#1179)", () => { + test("cold then warm /frag/today both render the fragment", async () => { + const cold = await fetch(`${base}/frag/today`); + expect(cold.status).toBe(200); + const coldBody = await cold.text(); + expect(coldBody).toContain('id="today-main"'); + // Warm hit: same fragment, served from the cache. + const warm = await fetch(`${base}/frag/today`); + expect(warm.status).toBe(200); + expect(await warm.text()).toBe(coldBody); + }); + + test("/today?full=1 and /api/today.json render from the same assembly", async () => { + const full = await fetch(`${base}/today?full=1`); + expect(full.status).toBe(200); + expect(await full.text()).toContain("Today"); + const api = await fetch(`${base}/api/today.json`); + expect(api.status).toBe(200); + const body = (await api.json()) as { objectives: unknown[]; momentum: unknown[] }; + expect(Array.isArray(body.objectives)).toBe(true); + expect(Array.isArray(body.momentum)).toBe(true); + }); + + test("the shell still serves without the full fan-out", async () => { + const shell = await fetch(`${base}/today`); + expect(shell.status).toBe(200); + const html = await shell.text(); + expect(html).toContain("/frag/today"); + }); +}); From 8dc39134896c0bd9e585853c0f4436b188c3dfbc Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 06:42:30 -0600 Subject: [PATCH 2/2] test(aggregator): explicit fixtures source for today-cache route test (main config drift) --- pm-stack/aggregator/test/today-cache-1179.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/pm-stack/aggregator/test/today-cache-1179.test.ts b/pm-stack/aggregator/test/today-cache-1179.test.ts index bb21685e03..239017d844 100644 --- a/pm-stack/aggregator/test/today-cache-1179.test.ts +++ b/pm-stack/aggregator/test/today-cache-1179.test.ts @@ -169,6 +169,7 @@ beforeAll(async () => { cwd: join(import.meta.dir, ".."), env: { ...Bun.env, + PM_AGG_SOURCE: "fixtures", PM_AGG_PORT: String(port), PM_AGG_FEED_FILE: join(dir, "no-feed.json"), PM_AGG_REGISTRY_FILE: join(dir, "registry.json"),