From 2ce9b99bb5a5523065455def5527f49791e9cdb4 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:01:07 +0530 Subject: [PATCH 1/5] Add in-memory report cache keyed by input and analysis version --- apps/backend/src/cache/analysis-version.ts | 35 ++++++++++ apps/backend/src/cache/report-cache.ts | 78 ++++++++++++++++++++++ apps/backend/src/cache/report-store.ts | 68 +++++++++++++++++++ apps/backend/src/config/env.ts | 9 +++ 4 files changed, 190 insertions(+) create mode 100644 apps/backend/src/cache/analysis-version.ts create mode 100644 apps/backend/src/cache/report-cache.ts create mode 100644 apps/backend/src/cache/report-store.ts diff --git a/apps/backend/src/cache/analysis-version.ts b/apps/backend/src/cache/analysis-version.ts new file mode 100644 index 0000000..3d1a20b --- /dev/null +++ b/apps/backend/src/cache/analysis-version.ts @@ -0,0 +1,35 @@ +import { createHash } from "node:crypto"; + +import { env } from "../config/env.js"; +import { + ANALYSIS_TASK, + REPORT_REQUIREMENTS, + SYSTEM_INSTRUCTION, +} from "../ai/prompt/prompt.constants.js"; +import { ENGINEERING_REPORT_JSON_SCHEMA } from "../ai/report/report.json-schema.js"; + +/** + * Bump when the pipeline changes in a way the fingerprint below cannot + * see (e.g. how files are ranked, filtered or formatted in the prompt), + * so cached reports from the old pipeline are no longer reused. + */ +const PIPELINE_REVISION = 1; + +/** + * Fingerprint of everything that shapes a report: model, settings, + * prompt text, output schema and pipeline revision. Part of every cache + * key, so changing any of them makes old cached reports stop matching. + */ +export const ANALYSIS_VERSION = createHash("sha256") + .update( + JSON.stringify({ + revision: PIPELINE_REVISION, + model: env.GEMINI_MODEL, + temperature: env.GEMINI_TEMPERATURE ?? null, + maxPromptTokens: env.MAX_PROMPT_TOKENS, + prompt: [SYSTEM_INSTRUCTION, ANALYSIS_TASK, REPORT_REQUIREMENTS], + schema: ENGINEERING_REPORT_JSON_SCHEMA, + }), + ) + .digest("hex") + .slice(0, 12); diff --git a/apps/backend/src/cache/report-cache.ts b/apps/backend/src/cache/report-cache.ts new file mode 100644 index 0000000..4843f63 --- /dev/null +++ b/apps/backend/src/cache/report-cache.ts @@ -0,0 +1,78 @@ +import fs from "node:fs"; +import { createHash } from "node:crypto"; +import { pipeline } from "node:stream/promises"; + +import { env } from "../config/env.js"; +import { jobStore } from "../jobs/job.store.js"; +import type { JobResult } from "../jobs/job.types.js"; +import { ANALYSIS_VERSION } from "./analysis-version.js"; +import { MemoryReportStore, type ReportStore } from "./report-store.js"; + +/** + * Cache key for a GitHub commit. The repository name is included so a + * fork with the same commit still gets a report labelled with its name. + */ +export function githubCacheKey(fullName: string, commitSha: string): string { + return `${ANALYSIS_VERSION}:github:${fullName.toLowerCase()}@${commitSha}`; +} + +/** + * Cache key for an uploaded ZIP: the SHA-256 of its bytes, so the same + * archive uploaded again (by anyone) reuses the report. + */ +export async function uploadCacheKey(zipPath: string): Promise { + const hash = createHash("sha256"); + + await pipeline(fs.createReadStream(zipPath), hash); + + return `${ANALYSIS_VERSION}:zip:${hash.digest("hex")}`; +} + +/** + * Reuses finished reports and joins identical analyses already running. + */ +export class ReportCache { + private readonly inFlight = new Map(); + + constructor(private readonly store: ReportStore) {} + + async lookup(key: string): Promise { + return this.store.get(key); + } + + async save(key: string, result: JobResult): Promise { + await this.store.set(key, result); + } + + /** + * Id of a job already analyzing this input, if one is still running. + */ + runningJob(key: string): string | undefined { + const jobId = this.inFlight.get(key); + + if (jobId && jobStore.get(jobId)?.status === "running") { + return jobId; + } + + this.inFlight.delete(key); + + return undefined; + } + + track(key: string, jobId: string): void { + this.inFlight.set(key, jobId); + } + + release(key: string, jobId: string): void { + if (this.inFlight.get(key) === jobId) { + this.inFlight.delete(key); + } + } +} + +export const reportCache = new ReportCache( + new MemoryReportStore( + env.REPORT_CACHE_MAX_ENTRIES, + env.REPORT_CACHE_TTL_HOURS * 60 * 60 * 1000, + ), +); diff --git a/apps/backend/src/cache/report-store.ts b/apps/backend/src/cache/report-store.ts new file mode 100644 index 0000000..72cb88e --- /dev/null +++ b/apps/backend/src/cache/report-store.ts @@ -0,0 +1,68 @@ +import type { JobResult } from "../jobs/job.types.js"; + +/** + * Where finished reports are kept for reuse. The in-memory store below + * is the default; a database-backed store can implement the same + * interface later (e.g. for saved, shareable reports). + */ +export interface ReportStore { + get(key: string): Promise; + set(key: string, result: JobResult): Promise; +} + +interface Entry { + result: JobResult; + expiresAt: number; +} + +/** + * Least-recently-used cache in process memory, with a time limit per + * entry. Cleared when the server restarts (or sleeps on Render's free + * plan). + */ +export class MemoryReportStore implements ReportStore { + private readonly entries = new Map(); + + constructor( + private readonly maxEntries: number, + private readonly ttlMs: number, + private readonly now: () => number = Date.now, + ) {} + + async get(key: string): Promise { + const entry = this.entries.get(key); + + if (!entry) { + return undefined; + } + + if (entry.expiresAt <= this.now()) { + this.entries.delete(key); + return undefined; + } + + // Map keeps insertion order: re-insert to mark as recently used. + this.entries.delete(key); + this.entries.set(key, entry); + + return entry.result; + } + + async set(key: string, result: JobResult): Promise { + if (this.maxEntries <= 0) { + return; + } + + this.entries.delete(key); + this.entries.set(key, { result, expiresAt: this.now() + this.ttlMs }); + + while (this.entries.size > this.maxEntries) { + const oldest = this.entries.keys().next().value as string; + this.entries.delete(oldest); + } + } + + get size(): number { + return this.entries.size; + } +} diff --git a/apps/backend/src/config/env.ts b/apps/backend/src/config/env.ts index db648d0..e6abc4e 100644 --- a/apps/backend/src/config/env.ts +++ b/apps/backend/src/config/env.ts @@ -40,6 +40,15 @@ const envSchema = z.object({ .string() .optional() .transform((value) => value?.trim() || undefined), + /** + * Finished reports kept in memory for reuse when the same GitHub + * commit or the same ZIP is analyzed again. 0 = no caching. + */ + REPORT_CACHE_MAX_ENTRIES: z.coerce.number().int().min(0).default(50), + /** + * How long a cached report is reused, in hours. + */ + REPORT_CACHE_TTL_HOURS: z.coerce.number().positive().default(168), /** * Upper bound on the prompt size sent to Gemini. Source files are * ranked by importance and added until this budget is reached. From 119b277a9b4cced545e3c25ed82cef7da7c92107 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:01:07 +0530 Subject: [PATCH 2/5] Reuse cached reports and join identical running analyses --- .../src/application/analysis-job.runner.ts | 23 ++- apps/backend/src/http/rate-limit.ts | 7 +- apps/backend/src/jobs/job.types.ts | 4 + apps/backend/src/routes/analyze.ts | 147 ++++++++++++------ apps/backend/test/github-route.test.ts | 1 + apps/backend/test/job-store.test.ts | 2 + apps/backend/test/rate-limit.test.ts | 11 +- 7 files changed, 140 insertions(+), 55 deletions(-) diff --git a/apps/backend/src/application/analysis-job.runner.ts b/apps/backend/src/application/analysis-job.runner.ts index 7c4c994..329ccb2 100644 --- a/apps/backend/src/application/analysis-job.runner.ts +++ b/apps/backend/src/application/analysis-job.runner.ts @@ -8,6 +8,7 @@ import { JobLogger } from "../logger/logger.service.js"; import { toErrorResponse } from "../http/error-response.js"; import { downloadRepositoryZip } from "../github/github.client.js"; import { MAX_UPLOAD_SIZE } from "../constants/upload.js"; +import { reportCache } from "../cache/report-cache.js"; import type { AnalysisSource, JobContext } from "../jobs/job.types.js"; import type { RepositoryInfo } from "../types/repository-info.js"; @@ -62,6 +63,11 @@ async function prepareSource( }; } +export interface RunOptions { + /** Store the result under this key for reuse. */ + cacheKey?: string; +} + /** * Runs one analysis job in the background and records the outcome * in the job store. Never throws: every failure becomes a failed job. @@ -69,6 +75,7 @@ async function prepareSource( export async function runAnalysisJob( jobId: string, source: AnalysisSource, + options: RunOptions = {}, ): Promise { const logger = new JobLogger(jobId); @@ -86,16 +93,28 @@ export async function runAnalysisJob( // Deletes the ZIP and extracted files when done. const result = await analyzeUploadedRepository(zipPath, context, repository); - jobStore.complete(jobId, { + const jobResult = { report: result.report, markdown: result.markdown, repository, - }); + analyzedAt: new Date().toISOString(), + cached: false, + }; + + if (options.cacheKey) { + await reportCache.save(options.cacheKey, jobResult); + } + + jobStore.complete(jobId, jobResult); await logger.info("Repository analysis completed", result.trace); } catch (error) { await logger.error("Repository analysis failed", error); jobStore.fail(jobId, toErrorResponse(error)); + } finally { + if (options.cacheKey) { + reportCache.release(options.cacheKey, jobId); + } } } diff --git a/apps/backend/src/http/rate-limit.ts b/apps/backend/src/http/rate-limit.ts index 5d80d9c..10f8b50 100644 --- a/apps/backend/src/http/rate-limit.ts +++ b/apps/backend/src/http/rate-limit.ts @@ -37,8 +37,9 @@ const passThrough: RequestHandler = (_req, _res, next) => next(); * rotate through addresses) * - whole site: RATE_LIMIT_PER_DAY analyses per day across all visitors * - * Only accepted analyses count: requests that end in an error - * (bad upload, server busy, limit reached) do not use up the limit. + * Only analyses that actually start (HTTP 202) count: errors (bad + * upload, server busy, limit reached) and reused results (a cached + * report, or joining an identical analysis already running) do not. * Runs before the upload is received, so a limited visitor cannot * send a large file first. * @@ -51,6 +52,7 @@ export const analysisRateLimits: RequestHandler[] = [ limit: env.RATE_LIMIT_PER_DAY, keyGenerator: () => "site", skipFailedRequests: true, + requestWasSuccessful: (_req, res) => res.statusCode === 202, standardHeaders: "draft-8", legacyHeaders: false, handler: (req, res) => { @@ -71,6 +73,7 @@ export const analysisRateLimits: RequestHandler[] = [ limit: env.RATE_LIMIT_PER_HOUR, keyGenerator: (req) => ipKeyGenerator(req.ip ?? "unknown"), skipFailedRequests: true, + requestWasSuccessful: (_req, res) => res.statusCode === 202, standardHeaders: "draft-8", legacyHeaders: false, handler: (req, res) => { diff --git a/apps/backend/src/jobs/job.types.ts b/apps/backend/src/jobs/job.types.ts index ad59e48..7bf7221 100644 --- a/apps/backend/src/jobs/job.types.ts +++ b/apps/backend/src/jobs/job.types.ts @@ -13,6 +13,10 @@ export interface JobResult { report: EngineeringReport; markdown: string; repository: RepositoryInfo; + /** When the analysis ran (ISO 8601). Older than now for cached results. */ + analyzedAt: string; + /** True when this result was reused from the cache. */ + cached: boolean; } /** diff --git a/apps/backend/src/routes/analyze.ts b/apps/backend/src/routes/analyze.ts index 9880276..a2c87ad 100644 --- a/apps/backend/src/routes/analyze.ts +++ b/apps/backend/src/routes/analyze.ts @@ -8,6 +8,12 @@ import { jobStore } from "../jobs/job.store.js"; import { env } from "../config/env.js"; import { parseGitHubUrl } from "../github/github-url.js"; import { resolveRepository } from "../github/github.client.js"; +import { + githubCacheKey, + reportCache, + uploadCacheKey, +} from "../cache/report-cache.js"; +import type { AnalysisSource } from "../jobs/job.types.js"; const router = Router(); @@ -15,21 +21,82 @@ function isBusy(): boolean { return jobStore.runningCount() >= env.MAX_CONCURRENT_JOBS; } -function sendBusy(res: Response) { - return res.status(429).json({ - success: false, - error: "SERVER_BUSY", - message: - "The server is busy with other analyses. Please try again in a minute.", - }); +/** + * Reuses a cached report, joins an identical analysis already running, + * or starts a new job. Responses: + * + * - 200 { jobId, cached: true } finished report from the cache + * - 200 { jobId, joined: true } same input is already being analyzed + * - 202 { jobId } new analysis started + * - 429 SERVER_BUSY too many analyses running + * + * Only 202 counts toward the rate limits. In every case the client + * follows GET /api/jobs/:id/events for the result. + * + * `cleanup` runs when the source is not needed (an uploaded ZIP that + * will not be analyzed). + */ +async function startOrReuse( + res: Response, + options: { + cacheKey: string; + force: boolean; + source: AnalysisSource; + cleanup?: () => Promise; + extra?: Record; + }, +) { + const { cacheKey, force, source, cleanup, extra } = options; + + if (!force) { + const cached = await reportCache.lookup(cacheKey); + + if (cached) { + await cleanup?.(); + + const job = jobStore.create(); + jobStore.complete(job.id, { ...cached, cached: true }); + + return res.status(200).json({ success: true, jobId: job.id, cached: true, ...extra }); + } + } + + const runningJobId = reportCache.runningJob(cacheKey); + + if (runningJobId) { + await cleanup?.(); + + return res.status(200).json({ success: true, jobId: runningJobId, joined: true, ...extra }); + } + + if (isBusy()) { + await cleanup?.(); + + return res.status(429).json({ + success: false, + error: "SERVER_BUSY", + message: + "The server is busy with other analyses. Please try again in a minute.", + }); + } + + const job = jobStore.create(); + + reportCache.track(cacheKey, job.id); + + void runAnalysisJob(job.id, source, { cacheKey }); + + return res.status(202).json({ success: true, jobId: job.id, ...extra }); } /** - * Accepts a ZIP upload and starts a background analysis job. + * Accepts a ZIP upload and starts (or reuses) an analysis. + * Form fields: `repository` (the ZIP), optional `force=true` to skip + * the cache and analyze again. * * Rate limits are checked before the upload is received. - * Responds immediately with 202 and a job id. Progress and the final - * report are delivered by GET /api/jobs/:id/events (Server-Sent Events). + * Progress and the final report are delivered by + * GET /api/jobs/:id/events (Server-Sent Events). */ router.post( "/analyze", @@ -44,35 +111,28 @@ router.post( }); } - if (isBusy()) { - await fs.rm(req.file.path, { force: true }); - - return sendBusy(res); - } - - const job = jobStore.create(); + const zipPath = req.file.path; - void runAnalysisJob(job.id, { - type: "upload", - zipPath: req.file.path, - fileName: req.file.originalname, - }); - - return res.status(202).json({ - success: true, - jobId: job.id, + return startOrReuse(res, { + cacheKey: await uploadCacheKey(zipPath), + force: req.body?.force === "true", + source: { + type: "upload", + zipPath, + fileName: req.file.originalname, + }, + cleanup: () => fs.rm(zipPath, { force: true }), }); }, ); /** - * Starts a background analysis of a public GitHub repository. - * Body: { "url": "https://github.com/owner/repo" } + * Starts (or reuses) an analysis of a public GitHub repository. + * Body: { "url": "https://github.com/owner/repo", "force"?: true } * - * The URL is checked and the repository looked up on GitHub before the - * job is created, so mistakes (typos, private repositories) are reported - * immediately and do not count toward the rate limit. The download - * itself happens inside the job. + * The URL is checked and the repository looked up on GitHub first, so + * mistakes (typos, private repositories) are reported immediately and + * do not count toward the rate limit. The download happens in the job. */ router.post( "/analyze/github", @@ -88,23 +148,18 @@ router.post( }); } - if (isBusy()) { - return sendBusy(res); - } - // Throws GitHubError, which the error handler turns into JSON. const repository = await resolveRepository(parseGitHubUrl(url)); - const job = jobStore.create(); - - void runAnalysisJob(job.id, { type: "github", repository }); - - return res.status(202).json({ - success: true, - jobId: job.id, - repository: { - name: repository.fullName, - commitSha: repository.commitSha, + return startOrReuse(res, { + cacheKey: githubCacheKey(repository.fullName, repository.commitSha), + force: req.body?.force === true, + source: { type: "github", repository }, + extra: { + repository: { + name: repository.fullName, + commitSha: repository.commitSha, + }, }, }); }, diff --git a/apps/backend/test/github-route.test.ts b/apps/backend/test/github-route.test.ts index 6046118..f3ddb86 100644 --- a/apps/backend/test/github-route.test.ts +++ b/apps/backend/test/github-route.test.ts @@ -94,6 +94,7 @@ describe("POST /api/analyze/github", () => { expect(vi.mocked(runAnalysisJob)).toHaveBeenCalledWith( started.body.jobId, { type: "github", repository }, + { cacheKey: expect.stringContaining(`:github:owner/repo@${"d".repeat(40)}`) }, ); }); diff --git a/apps/backend/test/job-store.test.ts b/apps/backend/test/job-store.test.ts index 232a74a..c12543f 100644 --- a/apps/backend/test/job-store.test.ts +++ b/apps/backend/test/job-store.test.ts @@ -37,6 +37,8 @@ describe("jobStore", () => { report, markdown: "# done", repository: { name: "demo" }, + analyzedAt: new Date().toISOString(), + cached: false, }); jobStore.fail(job.id, { status: 500, diff --git a/apps/backend/test/rate-limit.test.ts b/apps/backend/test/rate-limit.test.ts index f83af5a..12f48cc 100644 --- a/apps/backend/test/rate-limit.test.ts +++ b/apps/backend/test/rate-limit.test.ts @@ -23,13 +23,9 @@ const { default: app } = await import("../src/app.js"); let server: Server; let baseUrl: string; -let zipBytes: Buffer; +let uploads = 0; beforeAll(async () => { - zipBytes = await fs.readFile( - await createZip([{ name: "repo/index.ts", content: "export {};" }]), - ); - server = app.listen(0); await new Promise((resolve) => server.once("listening", resolve)); baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; @@ -44,6 +40,11 @@ afterAll(() => { * proxy would add). */ async function upload(ip: string, fileName = "repo.zip") { + // A different ZIP each time, so the report cache never applies here. + const zipBytes = await fs.readFile( + await createZip([{ name: "repo/index.ts", content: `export const n = ${uploads++};` }]), + ); + const form = new FormData(); form.append("repository", new Blob([new Uint8Array(zipBytes)]), fileName); From 7aaf9d247107238baee3f47556f9d52f490e43fe Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:01:07 +0530 Subject: [PATCH 3/5] Test report cache, joining and forced re-analysis --- apps/backend/test/report-cache-http.test.ts | 129 ++++++++++++++++++++ apps/backend/test/report-cache.test.ts | 81 ++++++++++++ 2 files changed, 210 insertions(+) create mode 100644 apps/backend/test/report-cache-http.test.ts create mode 100644 apps/backend/test/report-cache.test.ts diff --git a/apps/backend/test/report-cache-http.test.ts b/apps/backend/test/report-cache-http.test.ts new file mode 100644 index 0000000..f728bd7 --- /dev/null +++ b/apps/backend/test/report-cache-http.test.ts @@ -0,0 +1,129 @@ +import fs from "node:fs/promises"; +import type { AddressInfo } from "node:net"; +import type { Server } from "node:http"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +import { createZip } from "./helpers/zip.js"; + +process.env.RATE_LIMIT_PER_HOUR = "3"; +process.env.RATE_LIMIT_PER_DAY = "0"; +process.env.MAX_CONCURRENT_JOBS = "100"; + +vi.mock("../src/ai/gemini/gemini.client.js", () => ({ + generateContent: vi.fn(), +})); + +const { default: app } = await import("../src/app.js"); +const { generateContent } = await import("../src/ai/gemini/gemini.client.js"); +const { jobStore } = await import("../src/jobs/job.store.js"); + +const report = { + summary: { purpose: "p", description: "d" }, + technologyStack: { languages: [], frameworks: [], databases: [], tools: [], infrastructure: [] }, + architecture: { summary: "s", strengths: [], weaknesses: [], scalability: "x", maintainability: "y" }, + folderStructure: { score: 7, positives: [], negatives: [], recommendations: [] }, + codeQuality: { score: 7, positives: [], negatives: [], recommendations: [] }, + strengths: [], + weaknesses: [], + improvements: [], + resumeFeedback: { score: 7, summary: "s", strengths: [], improvements: [], bestResumeBullets: [] }, + interviewQuestions: [], +}; + +let server: Server; +let baseUrl: string; + +beforeAll(async () => { + vi.mocked(generateContent).mockResolvedValue({ text: JSON.stringify(report) }); + + server = app.listen(0); + await new Promise((resolve) => server.once("listening", resolve)); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterAll(() => { + server.close(); +}); + +async function zipBytes(content: string): Promise> { + return new Uint8Array( + await fs.readFile(await createZip([{ name: "repo/index.ts", content }])), + ); +} + +async function upload(bytes: Uint8Array, force = false) { + const form = new FormData(); + + if (force) { + form.append("force", "true"); + } + + form.append("repository", new Blob([bytes]), "demo.zip"); + + const response = await fetch(`${baseUrl}/api/analyze`, { + method: "POST", + body: form, + headers: { "X-Forwarded-For": "203.0.113.20" }, + }); + + return { + status: response.status, + body: (await response.json()) as { jobId: string; cached?: boolean; error?: string }, + }; +} + +async function finished(jobId: string) { + await vi.waitFor(() => { + expect(jobStore.get(jobId)?.status).not.toBe("running"); + }); + + return jobStore.get(jobId)!; +} + +describe("report cache over HTTP", () => { + it("reuses, re-analyzes on request, and only counts new analyses", async () => { + const a = await zipBytes("export const a = 1;"); + + // 1. New analysis (limit used: 1 of 3). + const first = await upload(a); + expect(first.status).toBe(202); + + const firstJob = await finished(first.body.jobId); + expect(firstJob.result?.cached).toBe(false); + expect(firstJob.result?.repository.name).toBe("demo"); + expect(generateContent).toHaveBeenCalledTimes(1); + + // 2. Same ZIP: cached report, no Gemini call, limit not used. + const second = await upload(a); + expect(second.status).toBe(200); + expect(second.body.cached).toBe(true); + + const secondJob = await finished(second.body.jobId); + expect(secondJob.result).toMatchObject({ + cached: true, + analyzedAt: firstJob.result?.analyzedAt, + markdown: firstJob.result?.markdown, + }); + expect(generateContent).toHaveBeenCalledTimes(1); + + // 3. Same ZIP with force: analyzed again (limit used: 2 of 3). + const forced = await upload(a, true); + expect(forced.status).toBe(202); + + const forcedJob = await finished(forced.body.jobId); + expect(forcedJob.result?.cached).toBe(false); + expect(generateContent).toHaveBeenCalledTimes(2); + + // 4. A different ZIP (limit used: 3 of 3). The cached hit in step 2 + // did not count, otherwise this would be rejected. + const other = await upload(await zipBytes("export const b = 2;")); + expect(other.status).toBe(202); + await finished(other.body.jobId); + + // 5. Limit reached: a forced re-analysis is a new analysis, so it is refused. + const blocked = await upload(a, true); + expect(blocked.status).toBe(429); + expect(blocked.body.error).toBe("RATE_LIMITED"); + expect(generateContent).toHaveBeenCalledTimes(3); + }); +}); diff --git a/apps/backend/test/report-cache.test.ts b/apps/backend/test/report-cache.test.ts new file mode 100644 index 0000000..9d8cd5a --- /dev/null +++ b/apps/backend/test/report-cache.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; + +import { MemoryReportStore } from "../src/cache/report-store.js"; +import { ReportCache, githubCacheKey } from "../src/cache/report-cache.js"; +import { jobStore } from "../src/jobs/job.store.js"; +import type { JobResult } from "../src/jobs/job.types.js"; + +function result(name: string): JobResult { + return { + report: {} as never, + markdown: `# ${name}`, + repository: { name }, + analyzedAt: "2026-11-22T00:00:00.000Z", + cached: false, + }; +} + +describe("MemoryReportStore", () => { + it("evicts the least recently used entry when full", async () => { + const store = new MemoryReportStore(2, 60_000); + + await store.set("a", result("a")); + await store.set("b", result("b")); + await store.get("a"); // "a" is now more recent than "b" + await store.set("c", result("c")); + + expect(await store.get("a")).toBeDefined(); + expect(await store.get("b")).toBeUndefined(); + expect(await store.get("c")).toBeDefined(); + }); + + it("expires entries after their time limit", async () => { + let now = 1_000; + const store = new MemoryReportStore(10, 500, () => now); + + await store.set("a", result("a")); + now = 1_400; + expect(await store.get("a")).toBeDefined(); + + now = 1_501; + expect(await store.get("a")).toBeUndefined(); + expect(store.size).toBe(0); + }); + + it("stores nothing when the size is 0 (caching off)", async () => { + const store = new MemoryReportStore(0, 60_000); + + await store.set("a", result("a")); + + expect(await store.get("a")).toBeUndefined(); + }); +}); + +describe("ReportCache", () => { + it("lets identical requests join a running job, until it finishes", () => { + const cache = new ReportCache(new MemoryReportStore(10, 60_000)); + const job = jobStore.create(); + + cache.track("key", job.id); + expect(cache.runningJob("key")).toBe(job.id); + + jobStore.complete(job.id, result("done")); + expect(cache.runningJob("key")).toBeUndefined(); + }); + + it("only releases the job it was tracking", () => { + const cache = new ReportCache(new MemoryReportStore(10, 60_000)); + const newer = jobStore.create(); + + cache.track("key", newer.id); + cache.release("key", "an-older-job-id"); + + expect(cache.runningJob("key")).toBe(newer.id); + }); + + it("keys GitHub reports by repository and exact commit", () => { + expect(githubCacheKey("Owner/Repo", "abc")).toBe(githubCacheKey("owner/repo", "abc")); + expect(githubCacheKey("owner/repo", "abc")).not.toBe(githubCacheKey("owner/fork", "abc")); + expect(githubCacheKey("owner/repo", "abc")).not.toBe(githubCacheKey("owner/repo", "def")); + }); +}); From 3cfaf0c86154b0efbf6a5ff12380692bb309e23c Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:01:07 +0530 Subject: [PATCH 4/5] Show cached report notice with a re-analyze option --- .../components/report/CachedResultNotice.tsx | 47 +++++++++++++++++++ .../src/components/report/ReportViewer.tsx | 13 +++++ apps/frontend/src/hooks/useAnalysis.ts | 47 +++++++++++++++---- apps/frontend/src/pages/HomePage.tsx | 10 +++- apps/frontend/src/services/api.ts | 8 ++++ apps/frontend/src/types/report.ts | 4 ++ 6 files changed, 118 insertions(+), 11 deletions(-) create mode 100644 apps/frontend/src/components/report/CachedResultNotice.tsx diff --git a/apps/frontend/src/components/report/CachedResultNotice.tsx b/apps/frontend/src/components/report/CachedResultNotice.tsx new file mode 100644 index 0000000..87c46fd --- /dev/null +++ b/apps/frontend/src/components/report/CachedResultNotice.tsx @@ -0,0 +1,47 @@ +import { History, RefreshCw } from "lucide-react"; + +interface Props { + analyzedAt: string; + loading: boolean; + onReanalyze(): void; +} + +/** + * Shown above a report that was reused from an earlier analysis of the + * same GitHub commit or the same ZIP. + */ +export default function CachedResultNotice({ + analyzedAt, + loading, + onReanalyze, +}: Props) { + const when = new Date(analyzedAt).toLocaleString(undefined, { + dateStyle: "medium", + timeStyle: "short", + }); + + return ( +
+

+ + + This exact code was analyzed before, so the report from{" "} + {when} was reused instantly. + +

+ + +
+ ); +} diff --git a/apps/frontend/src/components/report/ReportViewer.tsx b/apps/frontend/src/components/report/ReportViewer.tsx index debaf3a..a5e04cc 100644 --- a/apps/frontend/src/components/report/ReportViewer.tsx +++ b/apps/frontend/src/components/report/ReportViewer.tsx @@ -1,6 +1,7 @@ import type { AnalyzeRepositoryResponse } from "../../types/report"; import ArchitectureCard from "./ArchitectureCard"; +import CachedResultNotice from "./CachedResultNotice"; import CodeQualityCard from "./CodeQualityCard"; import FolderStructureCard from "./FolderStructureCard"; import ImprovementCard from "./ImprovementCard"; @@ -15,16 +16,28 @@ import WeaknessesCard from "./WeaknessesCard"; interface Props { result: AnalyzeRepositoryResponse; + loading: boolean; + onReanalyze(): void; } export default function ReportViewer({ result, + loading, + onReanalyze, }: Props) { const { report, markdown, repository } = result; return (
+ {result.cached && ( + + )} +
diff --git a/apps/frontend/src/hooks/useAnalysis.ts b/apps/frontend/src/hooks/useAnalysis.ts index bd2bc32..428d08d 100644 --- a/apps/frontend/src/hooks/useAnalysis.ts +++ b/apps/frontend/src/hooks/useAnalysis.ts @@ -50,6 +50,11 @@ export function useAnalysis() { const unsubscribeRef = useRef<(() => void) | null>(null); + // The last thing analyzed, so a cached report can be re-analyzed. + const lastRequestRef = useRef< + { type: "zip"; file: File } | { type: "github"; url: string } | null + >(null); + useEffect(() => () => unsubscribeRef.current?.(), []); function reset() { @@ -86,9 +91,10 @@ export function useAnalysis() { setProgress(FAILED); } - async function analyze(file: File) { + async function analyze(file: File, force = false) { unsubscribeRef.current?.(); reset(); + lastRequestRef.current = { type: "zip", file }; if (file.size > MAX_UPLOAD_SIZE) { setUploadTooLargeError(UPLOAD_TOO_LARGE); @@ -105,13 +111,17 @@ export function useAnalysis() { let jobId: string; try { - ({ jobId } = await startAnalysis(file, (fraction) => { - setProgress({ - stage: "UPLOADING", - message: `Uploading repository... ${Math.round(fraction * 100)}%`, - percentage: Math.round(fraction * 5), - }); - })); + ({ jobId } = await startAnalysis( + file, + (fraction) => { + setProgress({ + stage: "UPLOADING", + message: `Uploading repository... ${Math.round(fraction * 100)}%`, + percentage: Math.round(fraction * 5), + }); + }, + force, + )); } catch (requestError) { if (axios.isAxiosError(requestError)) { if ( @@ -170,12 +180,28 @@ export function useAnalysis() { }); } + /** + * Runs the last analysis again, skipping the cache. + */ + function reanalyze() { + const last = lastRequestRef.current; + + if (!last) return; + + if (last.type === "zip") { + void analyze(last.file, true); + } else { + void analyzeGithub(last.url, true); + } + } + /** * Analyzes a public GitHub repository by URL. */ - async function analyzeGithub(url: string) { + async function analyzeGithub(url: string, force = false) { unsubscribeRef.current?.(); reset(); + lastRequestRef.current = { type: "github", url }; setLoading(true); setProgress({ @@ -187,7 +213,7 @@ export function useAnalysis() { let jobId: string; try { - ({ jobId } = await startGithubAnalysis(url)); + ({ jobId } = await startGithubAnalysis(url, force)); } catch (requestError) { if (axios.isAxiosError(requestError) && requestError.response) { handleFailure( @@ -217,6 +243,7 @@ export function useAnalysis() { progress, analyze, analyzeGithub, + reanalyze, reset, }; } diff --git a/apps/frontend/src/pages/HomePage.tsx b/apps/frontend/src/pages/HomePage.tsx index 54cfe90..9f96015 100644 --- a/apps/frontend/src/pages/HomePage.tsx +++ b/apps/frontend/src/pages/HomePage.tsx @@ -31,6 +31,7 @@ export default function HomePage() { const { analyze, analyzeGithub, + reanalyze, loading, error, result, @@ -112,7 +113,14 @@ export default function HomePage() { {result && (
- + { + setShowProgress(true); + reanalyze(); + }} + />
)} diff --git a/apps/frontend/src/services/api.ts b/apps/frontend/src/services/api.ts index ca4b173..774068d 100644 --- a/apps/frontend/src/services/api.ts +++ b/apps/frontend/src/services/api.ts @@ -18,9 +18,15 @@ const api = axios.create({ export async function startAnalysis( file: File, onUploadProgress?: (fraction: number) => void, + force = false, ): Promise<{ jobId: string }> { const formData = new FormData(); + if (force) { + // Skip the cache and analyze again. + formData.append("force", "true"); + } + formData.append("repository", file); const response = await api.post<{ jobId: string }>( @@ -45,9 +51,11 @@ export async function startAnalysis( */ export async function startGithubAnalysis( url: string, + force = false, ): Promise<{ jobId: string }> { const response = await api.post<{ jobId: string }>("/analyze/github", { url, + ...(force ? { force: true } : {}), }); return response.data; diff --git a/apps/frontend/src/types/report.ts b/apps/frontend/src/types/report.ts index b84750e..746c35c 100644 --- a/apps/frontend/src/types/report.ts +++ b/apps/frontend/src/types/report.ts @@ -27,4 +27,8 @@ export interface AnalyzeRepositoryResponse { report: EngineeringReport; markdown: string; repository: RepositoryInfo; + /** When the analysis ran (ISO 8601). */ + analyzedAt: string; + /** True when the same input was analyzed before and the report reused. */ + cached: boolean; } From 1527a0a12157ac51539a7d4ec1a0fdfd4094c7e3 Mon Sep 17 00:00:00 2001 From: Atul Boyal Date: Sun, 22 Nov 2026 23:01:07 +0530 Subject: [PATCH 5/5] Document report caching --- README.md | 19 ++++++++++++++++--- apps/backend/.env.example | 5 +++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f37cd81..d3a86e7 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,11 @@ MAX_CONCURRENT_JOBS=2 # token with no extra permissions is enough (public repositories only). # GITHUB_TOKEN=github_pat_... +# Optional: reuse reports when the same GitHub commit or the same ZIP is +# analyzed again (in memory; cleared on restart). 0 entries = no caching. +REPORT_CACHE_MAX_ENTRIES=50 +REPORT_CACHE_TTL_HOURS=168 + # Optional: rate limits on starting analyses (0 = no limit) RATE_LIMIT_PER_HOUR=5 # per visitor (IP address) RATE_LIMIT_PER_DAY=100 # whole site @@ -351,13 +356,21 @@ SAVE_DEBUG_ARTIFACTS=false | Method | Path | Description | |---|---|---| -| `POST` | `/api/analyze` | Upload a ZIP (`repository` form field). Returns `202 { jobId }`. | -| `POST` | `/api/analyze/github` | JSON `{ "url": "https://github.com/owner/repo" }`. Public repositories only; checked on GitHub before the job starts. Returns `202 { jobId, repository }`. | +| `POST` | `/api/analyze` | Upload a ZIP (`repository` form field; optional `force=true`). | +| `POST` | `/api/analyze/github` | JSON `{ "url": "https://github.com/owner/repo", "force"?: true }`. Public repositories only; checked on GitHub before the job starts. | | `GET` | `/api/jobs/:id/events` | Server-Sent Events: `progress`, then `completed` (report + markdown) or `failed` (error body). | | `GET` | `/api/jobs/:id` | Current job state as JSON. | | `GET` | `/api/health` | Health check. | -Starting an analysis is rate limited per visitor and per day for the whole site (HTTP 429 with a message saying when to retry). Only accepted analyses count, and limits are checked before the upload is received. +Both analyze endpoints return a `jobId` to follow: + +- `202` a new analysis started +- `200 { cached: true }` the same GitHub commit or the same ZIP (by SHA-256) was analyzed before, so the stored report is returned instantly +- `200 { joined: true }` the same input is already being analyzed, so the request shares that job + +Cached reports are keyed by an analysis version (model, settings, prompt and schema), so changing any of those stops old reports from being reused. `force` skips the cache. + +Starting an analysis is rate limited per visitor and per day for the whole site (HTTP 429 with a message saying when to retry). Only new analyses (`202`) count, not cached or joined results, and limits are checked before the upload is received. Each analysis runs as its own job, so concurrent users never see each other's progress. Finished jobs are kept in memory for 30 minutes. diff --git a/apps/backend/.env.example b/apps/backend/.env.example index 68ad4ea..47149ab 100644 --- a/apps/backend/.env.example +++ b/apps/backend/.env.example @@ -10,6 +10,11 @@ MAX_CONCURRENT_JOBS=2 # A fine-grained token with no extra permissions is enough (public repos only). # GITHUB_TOKEN= +# Reuse reports when the same GitHub commit or ZIP is analyzed again +# (in memory; cleared on restart). 0 entries = no caching. +REPORT_CACHE_MAX_ENTRIES=50 +REPORT_CACHE_TTL_HOURS=168 + # Rate limits on starting analyses (0 = no limit). # Per visitor (IP address) per hour, and for the whole site per day. RATE_LIMIT_PER_HOUR=5