From 8764ecaf81794738175e6adc5f5ac4f6d8fb06a0 Mon Sep 17 00:00:00 2001 From: hltav Date: Wed, 4 Nov 2026 01:16:25 -0300 Subject: [PATCH 1/4] =?UTF-8?q?perf(PAV-187):=20reduz=20normaliza=C3=A7?= =?UTF-8?q?=C3=B5es=20redundantes=20nos=20filtros?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../modules/jobs/filters/jobSearch.filter.ts | 49 ++++++------- .../modules/jobs/jobSearch.filter.test.ts | 73 +++++++++++++++++++ 2 files changed, 94 insertions(+), 28 deletions(-) diff --git a/backend/src/modules/jobs/filters/jobSearch.filter.ts b/backend/src/modules/jobs/filters/jobSearch.filter.ts index 4642ee0..74c6eb3 100644 --- a/backend/src/modules/jobs/filters/jobSearch.filter.ts +++ b/backend/src/modules/jobs/filters/jobSearch.filter.ts @@ -68,36 +68,33 @@ function inferJobLevel(title: string): string { return "pleno"; } +// Match the separator run that normalizeComparable would turn into one space. +// Do not use \s: punctuation and Unicode separators must keep matching too. +const HOME_OFFICE_PATTERN = /home[^\p{L}\p{N}]+office/u; + function inferJobType(job: SearchJob): string { - const normalized = normalizeComparable( - [job.title, job.location, job.modality, job.description] - .filter(Boolean) - .join(" "), - ); + // Stems contain only letters: replacing separators cannot create a match. + // Keep the full description and hybrid precedence, including conflicting fields. + const normalized = [job.title, job.location, job.modality, job.description] + .filter(Boolean) + .join(" ") + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .toLowerCase(); if (normalized.includes("hibrid") || normalized.includes("hybrid")) { return "hibrido"; } if ( normalized.includes("remot") || - normalized.includes("home office") || + HOME_OFFICE_PATTERN.test(normalized) || normalized.includes("teletrabalho") || normalized.includes("anywhere") || normalized.includes("worldwide") ) { return "remoto"; } - if ( - normalized.includes("presencial") || - normalized.includes("onsite") || - normalized.includes("on site") || - normalized.includes("on-site") || - normalized.includes("in office") || - normalized.includes("escritorio") - ) { - return "presencial"; - } - + // All explicit onsite aliases and documents without evidence use this fallback. return "presencial"; } @@ -242,15 +239,10 @@ export function inferJobLocationParts(location: string): JobLocationParts { return parts; } -function inferLocationCountry(location: string): string { - return inferJobLocationParts(location).country; -} - -function matchesLocationFilter(jobLocation: string, location: string): boolean { +function matchesLocationFilter(jobLocation: string, location: string, inferredCountry: string): boolean { if (!location) return true; const normalizedLocation = normalizeComparable(jobLocation); - const inferredCountry = inferLocationCountry(jobLocation); if (inferredCountry) return inferredCountry === location; return normalizedLocation.includes(location); @@ -307,6 +299,7 @@ export function filterJobs( const families = filters.families.map(normalizeComparable); const technologies = filters.technology.map(normalizeComparable); const companies = filters.company.map(normalizeComparable); + const needsLocation = Boolean(location || continent || state || city); if ( !level && @@ -348,20 +341,20 @@ export function filterJobs( !seniority || classifiedSeniority === seniority || inferJobLevel(title) === seniority; - const locationParts = inferJobLocationParts(jobLocation); - const matchesLocation = matchesLocationFilter(jobLocation, location); + const locationParts = needsLocation ? inferJobLocationParts(jobLocation) : undefined; + const matchesLocation = matchesLocationFilter(jobLocation, location, locationParts?.country ?? ""); const matchesContinent = matchesLocationPart( - locationParts.continent, + locationParts?.continent ?? "", jobLocation, continent, ); const matchesState = matchesLocationPart( - locationParts.state, + locationParts?.state ?? "", jobLocation, state, ); const matchesCity = matchesLocationPart( - locationParts.city, + locationParts?.city ?? "", jobLocation, city, ); diff --git a/backend/tests/unit/modules/jobs/jobSearch.filter.test.ts b/backend/tests/unit/modules/jobs/jobSearch.filter.test.ts index 0df3637..f2feda5 100644 --- a/backend/tests/unit/modules/jobs/jobSearch.filter.test.ts +++ b/backend/tests/unit/modules/jobs/jobSearch.filter.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { filterJobs, + normalizeComparable, inferJobLocationParts, sortJobsByMatch, } from "../../../../src/modules/jobs/filters/jobSearch.filter"; @@ -75,6 +76,20 @@ describe("inferJobLocationParts", () => { }); describe("filterJobs", () => { + it("preserva fallback textual e precedência do país em filtros combinados", () => { + const data = [ + { id: "known", company: "Acme", location: "Toronto, Canadá" }, + { id: "unknown", company: "Acme", location: "Atlantis Central" }, + { id: "empty", company: "Acme" }, + ]; + const ids = (query: Record) => + filterJobs(data, filters(query)).map((job) => (job as { id: string }).id); + expect(ids({ company: "acme" })).toEqual(["known", "unknown", "empty"]); + expect(ids({ location: "atlantis", company: "acme" })).toEqual(["unknown"]); + expect(ids({ country: "Canadá", location: "atlantis", city: "Toronto" })).toEqual(["known"]); + expect(ids({ country: "Brasil", city: "Toronto" })).toEqual([]); + }); + it("devolve tudo quando não há filtros", () => { expect(filterJobs(JOBS, filters({}))).toHaveLength(3); }); @@ -148,3 +163,61 @@ describe("sortJobsByMatch", () => { ]); }); }); + + +describe("inferência de modalidade sem normalizar separadores do documento inteiro", () => { + const cases: [string, Record, string][] = [ + ["remoto explícito", { modality: "Remoto" }, "remoto"], + ["híbrido explícito", { modality: "HÍBRIDO" }, "hibrido"], + ["presencial explícito", { modality: "Presencial" }, "presencial"], + ["ausente", {}, "presencial"], + ["sem descrição", { title: "Remote engineer" }, "remoto"], + ["híbrido inglês", { description: "HYBRID working" }, "hibrido"], + ["acentos", { description: "Trabalho RÉMÓTO" }, "remoto"], + ["home office", { description: "HOME OFFICE" }, "remoto"], + ["pontuação", { description: "home---office" }, "remoto"], + ["separadores Unicode", { description: "home\u00a0—\nOFFICE" }, "remoto"], + ["letra entre palavras", { description: "home界office" }, "presencial"], + ["número entre palavras", { description: "home1office" }, "presencial"], + ["sem separador", { description: "homeoffice" }, "presencial"], + ["frase entre campos", { title: "home", location: "office" }, "remoto"], + ["teletrabalho", { description: "TELETRABALHO" }, "remoto"], + ["anywhere", { location: "Anywhere" }, "remoto"], + ["worldwide", { location: "Worldwide" }, "remoto"], + ["onsite", { description: "Onsite" }, "presencial"], + ["on-site", { description: "On-Site" }, "presencial"], + ["in office", { description: "In Office" }, "presencial"], + ["escritório", { description: "ESCRITÓRIO" }, "presencial"], + ["descrição híbrida vence remoto estruturado", { modality: "Remote", description: "HYBRID" }, "hibrido"], + ["híbrido estruturado vence descrição remota", { modality: "Hybrid", description: "Remote" }, "hibrido"], + ["remoto vence presencial", { modality: "Presencial", description: "Remote" }, "remoto"], + ["todos os termos", { description: "Presencial, remote, híbrido" }, "hibrido"], + ["acento decomposto", { description: "hi\u0301brido" }, "hibrido"], + ]; + + it.each(cases)("preserva %s", (_name, data, expected) => { + const job = { id: "test", ...data }; + for (const type of ["remoto", "hibrido", "presencial"]) { + expect(filterJobs([job], filters({ type })).length).toBe(type === expected ? 1 : 0); + } + }); + + it("mantém IDs e ordem da regra anterior com combinações de campos e Unicode", () => { + const terms = ["", "Remote", "Híbrido", "Onsite", "home", "office", "home---office", "home界office", "home1office", "teletrabalho", "Worldwide", "hi\u0301brido"]; + const data = terms.flatMap((modality, i) => terms.map((description, j) => ({ + id: `${i}-${j}`, title: i % 2 ? "home" : "Engineer", company: "Acme", + location: "Brasil", modality, description, + }))); + function previousType(job: typeof data[number]) { + const text = normalizeComparable([job.title, job.location, job.modality, job.description].filter(Boolean).join(" ")); + if (text.includes("hibrid") || text.includes("hybrid")) return "hibrido"; + if (["remot", "home office", "teletrabalho", "anywhere", "worldwide"].some(alias => text.includes(alias))) return "remoto"; + return "presencial"; + } + for (const type of ["remoto", "hibrido", "presencial", "remoto,hibrido"]) { + const expected = data.filter(job => type.split(",").includes(previousType(job))).map(job => job.id); + const actual = filterJobs(data, filters({ type, company: "acme", country: "Brasil" })); + expect(actual.map(job => (job as { id: string }).id)).toEqual(expected); + } + }); +}); From 38fc183ed3ce665bea6dccefc5bec828d522b3c5 Mon Sep 17 00:00:00 2001 From: hltav Date: Wed, 4 Nov 2026 01:16:28 -0300 Subject: [PATCH 2/4] =?UTF-8?q?chore(PAV-187):=20adiciona=20diagn=C3=B3sti?= =?UTF-8?q?co=20agregado=20de=20busca?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jobs/repositories/jobSearch.repository.ts | 81 ++++++++++++++----- .../modules/jobs/jobSearch.repository.test.ts | 51 ++++++++++++ 2 files changed, 112 insertions(+), 20 deletions(-) diff --git a/backend/src/modules/jobs/repositories/jobSearch.repository.ts b/backend/src/modules/jobs/repositories/jobSearch.repository.ts index c9020b1..422c2a4 100644 --- a/backend/src/modules/jobs/repositories/jobSearch.repository.ts +++ b/backend/src/modules/jobs/repositories/jobSearch.repository.ts @@ -1,3 +1,5 @@ +import { performance } from "node:perf_hooks"; +import { logger } from "../../../logger"; import { searchPageCache } from "../cache/valkeySearchCache.adapter"; import { openIndexedSearch } from "./valkeyJobSearch.adapter"; import { @@ -43,6 +45,18 @@ export class JobSearchRepository { enrich?: (jobs: unknown[]) => Promise, priorityKeywords: string[] = [], ): Promise<{ jobs: unknown[]; total: number }> { + // Opt-in: only aggregate timings/counts; never log filters, IDs or profile data. + const diagnostics = process.env.JOB_SEARCH_DIAGNOSTICS === "1"; + const clock = () => (diagnostics ? performance.now() : 0); + const started = clock(); + let batches = 0; + let hydratedDocuments = 0; + let matchedDocuments = 0; + let returnedDocuments = 0; + let hydrationMs = 0; + let filterMs = 0; + let matchMs = 0; + let rankingMs = 0; const indexed = await openIndexedSearch(filters, priorityKeywords); const ids = indexed ? [] @@ -68,11 +82,22 @@ export class JobSearchRepository { for (let cursor = 0; cursor < ids.length; cursor += BATCH_SIZE) yield await cacheGetJobsByIds(ids.slice(cursor, cursor + BATCH_SIZE)); } + const candidatesMs = clock() - started; + let hydrationStarted = clock(); try { for await (const batch of indexed ? indexed.batches() : legacyBatches()) { + hydrationMs += clock() - hydrationStarted; + batches++; + hydratedDocuments += batch.length; + const filterStarted = clock(); const matches = filterJobs(batch, filters); + filterMs += clock() - filterStarted; + matchedDocuments += matches.length; if (filters.matchSort && enrich) { + const matchStarted = clock(); const jobs = await enrich(matches); + matchMs += clock() - matchStarted; + const rankingStarted = clock(); const candidates = jobs.map((job, index) => ({ id: String((job as { id: string }).id), rank: total + index, @@ -83,38 +108,54 @@ export class JobSearchRepository { ranked = [...ranked, ...candidates] .sort(compare) .slice(0, capacity); + rankingMs += clock() - rankingStarted; } else { for (const job of matches) { if (total >= offset && page.length < pagination.limit) page.push(job); total++; } + hydrationStarted = clock(); continue; } total += matches.length; + hydrationStarted = clock(); } - if (indexed && filters.matchSort && enrich) { - page.push( - ...(await indexed.hydrate( - await indexed.rankedIds(offset, pagination.limit, total), - )), - ); + hydrationMs += clock() - hydrationStarted; + let resultJobs = page; + if (filters.matchSort && enrich) { + let pageIds: string[]; + if (indexed) { + const rankingStarted = clock(); + pageIds = await indexed.rankedIds(offset, pagination.limit, total); + rankingMs += clock() - rankingStarted; + } else { + pageIds = ranked + .slice(offset, offset + pagination.limit) + .map((item) => item.id); + } + const pageHydrationStarted = clock(); + resultJobs = indexed + ? await indexed.hydrate(pageIds) + : await cacheGetJobsByIds(pageIds); + hydrationMs += clock() - pageHydrationStarted; + hydratedDocuments += resultJobs.length; } + returnedDocuments = resultJobs.length; + return { jobs: resultJobs, total }; } finally { - await indexed?.close(); + try { + await indexed?.close(); + } finally { + if (diagnostics) { + logger.info({ + durationMs: clock() - started, + candidatesMs, hydrationMs, filterMs, matchMs, rankingMs, + batches, hydratedDocuments, matchedDocuments, returnedDocuments, total, + indexed: Boolean(indexed), matchSorted: Boolean(filters.matchSort), + }, "Diagnóstico agregado da busca de vagas"); + } + } } - return { - jobs: - filters.matchSort && enrich - ? indexed - ? page - : await cacheGetJobsByIds( - ranked - .slice(offset, offset + pagination.limit) - .map((item) => item.id), - ) - : page, - total, - }; } } diff --git a/backend/tests/unit/modules/jobs/jobSearch.repository.test.ts b/backend/tests/unit/modules/jobs/jobSearch.repository.test.ts index 2023d3e..6fe1444 100644 --- a/backend/tests/unit/modules/jobs/jobSearch.repository.test.ts +++ b/backend/tests/unit/modules/jobs/jobSearch.repository.test.ts @@ -1,6 +1,9 @@ vi.mock("../../../../src/modules/jobs/repositories/valkeyJobSearch.adapter", () => ({ openIndexedSearch: vi.fn().mockResolvedValue(null), hasActiveJobIndex: vi.fn().mockResolvedValue(false) })); vi.mock("../../../../src/modules/jobs/cache/valkeySearchCache.adapter", () => ({ searchPageCache: {search: async (_f: unknown, _p: unknown, _r: unknown, query: () => Promise) => query()} })); import { beforeEach, describe, expect, it, vi } from "vitest"; +vi.mock("../../../../src/logger", () => ({ logger: { info: vi.fn() } })); +import { logger } from "../../../../src/logger"; +import { openIndexedSearch } from "../../../../src/modules/jobs/repositories/valkeyJobSearch.adapter"; vi.mock("../../../../src/lib/cache", () => ({ cacheAbsoluteSMembers: vi.fn(), cacheGetJobsByIds: vi.fn(), @@ -49,6 +52,54 @@ beforeEach(() => { seed(jobs); }); describe("persisted family search", () => { + it("inclui a hidratação final do ranking no diagnóstico indexado", async () => { + const data = [{ id: "a", matchScore: 90 }, { id: "b", matchScore: 80 }]; + const indexed = { + async *batches() { yield data; }, + rank: vi.fn().mockResolvedValue(undefined), + rankedIds: vi.fn().mockResolvedValue(["a"]), + hydrate: vi.fn().mockResolvedValue([data[0]]), + close: vi.fn().mockResolvedValue(undefined), + }; + vi.mocked(openIndexedSearch).mockResolvedValueOnce(indexed); + vi.stubEnv("JOB_SEARCH_DIAGNOSTICS", "1"); + try { + const result = await repository.search( + parseJobSearchQuery({ matchSort: "desc" }), + { page: 1, limit: 1 }, async (batch) => batch, + ); + expect(result).toEqual({ total: 2, jobs: [data[0]] }); + expect(indexed.close).toHaveBeenCalledOnce(); + expect(indexed.rankedIds).toHaveBeenCalledWith(0, 1, 2); + expect(logger.info).toHaveBeenCalledWith(expect.objectContaining({ + batches: 1, hydratedDocuments: 3, matchedDocuments: 2, + returnedDocuments: 1, total: 2, indexed: true, matchSorted: true, + }), "Diagnóstico agregado da busca de vagas"); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("diagnostica a varredura além da página sem registrar documentos ou filtros", async () => { + const data = Array.from({ length: 605 }, (_, i) => ({ id: String(i) })); + seed(data); + vi.stubEnv("JOB_SEARCH_DIAGNOSTICS", "1"); + try { + const result = await search({}, 1, 50); + expect(result.total).toBe(605); + expect(result.jobs).toHaveLength(50); + expect(logger.info).toHaveBeenCalledWith({ + durationMs: expect.any(Number), candidatesMs: expect.any(Number), + hydrationMs: expect.any(Number), filterMs: expect.any(Number), + matchMs: expect.any(Number), rankingMs: expect.any(Number), + batches: 4, hydratedDocuments: 605, matchedDocuments: 605, + returnedDocuments: 50, total: 605, indexed: false, matchSorted: false, + }, "Diagnóstico agregado da busca de vagas"); + } finally { + vi.unstubAllEnvs(); + } + }); + it.each([ ["backend", "primary", ["backend"]], ["backend", "any", ["backend", "leadership"]], From a5f342762f42c85af1dcdf51ca1f9f94ff430050 Mon Sep 17 00:00:00 2001 From: hltav Date: Fri, 6 Nov 2026 21:36:13 -0300 Subject: [PATCH 3/4] =?UTF-8?q?fix(PAV-187):=20protege=20cache=20contra=20?= =?UTF-8?q?mudan=C3=A7as=20de=20gera=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/lib/errors.ts | 1 + .../src/modules/jobs/cache/jobSearchCache.ts | 142 +++++++++--------- .../tests/unit/metrics/operational.test.ts | 8 +- .../unit/middleware/errorHandler.test.ts | 7 + .../unit/modules/jobs/jobSearchCache.test.ts | 92 +++++++++++- 5 files changed, 168 insertions(+), 82 deletions(-) diff --git a/backend/src/lib/errors.ts b/backend/src/lib/errors.ts index f234612..23bd82f 100644 --- a/backend/src/lib/errors.ts +++ b/backend/src/lib/errors.ts @@ -8,6 +8,7 @@ export type ErrorCode = | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" + | "SEARCH_CATALOG_UNAVAILABLE" | "INTERNAL_ERROR"; export type ErrorDetails = Record; diff --git a/backend/src/modules/jobs/cache/jobSearchCache.ts b/backend/src/modules/jobs/cache/jobSearchCache.ts index fe89e78..46ac0e8 100644 --- a/backend/src/modules/jobs/cache/jobSearchCache.ts +++ b/backend/src/modules/jobs/cache/jobSearchCache.ts @@ -5,6 +5,15 @@ import { import { jobSearchCacheKey } from "./jobSearchFingerprint"; import type { PaginationParams } from "../../../lib/pagination"; import type { ParsedJobSearchQuery } from "../types/jobSearch.types"; +import { AppError } from "../../../lib/errors"; + +class GenerationChanged extends Error { + constructor(readonly reason = "generation_changed") { super(reason); } +} + +function unavailable(reason: string): AppError { + return new AppError("SEARCH_CATALOG_UNAVAILABLE", "Catálogo de vagas temporariamente indisponível. Tente novamente.", 503, { reason }); +} export type SearchPage = { jobs: unknown[]; total: number }; export interface SearchCacheStore { @@ -21,7 +30,7 @@ export interface SearchCacheStore { /** Local single-flight combines simultaneous identical queries without reusing * the scraper execution lock. Failures never remain in the in-flight map. - * Cache lookup/publication failures degrade to the normal repository query. + * Page-cache failures may degrade to a query; catalog fences must remain valid. */ export class JobSearchCache { private readonly inFlight = new Map>(); @@ -43,85 +52,70 @@ export class JobSearchCache { rankingContext: unknown, query: () => Promise, ): Promise { - let generation: string | null; + let outcome: "hit" | "miss" | "stale" | "error" = "miss"; try { - const end = searchCacheDuration.startTimer({ operation: "get" }); - try { - generation = await this.store.generation(); - } finally { - end(); - } - } catch { - searchCacheRequests.inc({ result: "error" }); - return query(); - } - // null means indexes are unavailable or being rebuilt; do not cache. - if (generation === null) { - searchCacheRequests.inc({ result: "stale" }); - return query(); - } - const key = jobSearchCacheKey( - filters, - pagination, - generation, - rankingContext, - ); - const existing = this.inFlight.get(key); - if (existing) { - searchCacheRequests.inc({ result: "hit" }); - return structuredClone(await existing); - } - - const pending = (async () => { - let outcome: "hit" | "miss" | "stale" | "error" = "miss"; - try { - try { - const end = searchCacheDuration.startTimer({ operation: "get" }); - let cached; - let current; - try { - cached = await this.store.read(key); - current = await this.store.generation(); - } finally { - end(); - } - if (cached && current === generation) { - outcome = "hit"; - return cached; - } - outcome = cached ? "stale" : "miss"; - } catch { - outcome = "error"; - // A cache outage must not hide a successful persistence query. + // At most one reconstruction, shared under each generation's fingerprint. + for (let attempt = 0; attempt < 2; attempt++) { + const generation = await this.readGeneration(); + const key = jobSearchCacheKey(filters, pagination, generation, rankingContext); + let pending = this.inFlight.get(key); + if (pending) outcome = "hit"; + else { + pending = (async () => { + let cached: SearchPage | null = null; + const getEnd = searchCacheDuration.startTimer({ operation: "get" }); + try { cached = await this.store.read(key); } + catch { outcome = "error"; } + finally { getEnd(); } + if (cached) { outcome = "hit"; return cached; } + await this.requireGeneration(generation); + const page = await query(); + await this.requireGeneration(generation); + let published: boolean | undefined; + const setEnd = searchCacheDuration.startTimer({ operation: "set" }); + try { + published = await this.store.writeIfGeneration(key, page, generation, this.ttlSeconds); + } catch { outcome = "error"; } + finally { setEnd(); } + if (published === false) throw new GenerationChanged("publication_rejected"); + return page; + })(); + this.inFlight.set(key, pending); } - const page = await query(); try { - const end = searchCacheDuration.startTimer({ operation: "set" }); - try { - const published = await this.store.writeIfGeneration( - key, - page, - generation, - this.ttlSeconds, - ); - if (!published && outcome !== "error") outcome = "stale"; - } finally { - end(); - } - } catch { - outcome = "error"; - // The query remains useful; the next request can repopulate the cache. + const page = structuredClone(await pending); + // Also fences hits, shared results and changes during publication. + await this.requireGeneration(generation); + return page; + } catch (error) { + if (!(error instanceof GenerationChanged)) throw error; + outcome = "stale"; + if (attempt === 1) throw unavailable(error.reason); + } finally { + if (this.inFlight.get(key) === pending) this.inFlight.delete(key); } - return page; - } finally { - searchCacheRequests.inc({ result: outcome }); } - })(); - this.inFlight.set(key, pending); - try { - return structuredClone(await pending); + throw unavailable("generation_changed"); + } catch (error) { + if (error instanceof AppError && error.details?.reason === "catalog_unavailable") outcome = "stale"; + else if (!(error instanceof AppError && ["generation_changed", "publication_rejected"].includes(String(error.details?.reason)))) outcome = "error"; + throw error; } finally { - this.inFlight.delete(key); + searchCacheRequests.inc({ result: outcome }); } } + + private async readGeneration(): Promise { + const end = searchCacheDuration.startTimer({ operation: "get" }); + let generation: string | null; + try { generation = await this.store.generation(); } + catch { throw unavailable("generation_read_failed"); } + finally { end(); } + if (generation === null) throw unavailable("catalog_unavailable"); + return generation; + } + + private async requireGeneration(expected: string): Promise { + if (await this.readGeneration() !== expected) throw new GenerationChanged(); + } } diff --git a/backend/tests/unit/metrics/operational.test.ts b/backend/tests/unit/metrics/operational.test.ts index bd39953..cc7767f 100644 --- a/backend/tests/unit/metrics/operational.test.ts +++ b/backend/tests/unit/metrics/operational.test.ts @@ -47,7 +47,7 @@ describe("operational metrics cardinality and cache", () => { if (result === "stale") storage.generation.mockResolvedValue(null); if (result === "error") storage.generation.mockRejectedValue(new Error("secret free error")); - await new JobSearchCache(storage).search( + const search = new JobSearchCache(storage).search( parseJobSearchQuery({ family: "product", keywords: "private free text", @@ -56,6 +56,8 @@ describe("operational metrics cardinality and cache", () => { null, async () => ({ jobs: [], total: 0 }), ); + if (["stale", "error"].includes(result)) await expect(search).rejects.toMatchObject({ statusCode: 503 }); + else await search; expect((await searchCacheRequests.get()).values).toContainEqual( expect.objectContaining({ labels: { result }, value: 1 }), ); @@ -125,12 +127,12 @@ it("records a rejected generation publication as stale", async () => { read: vi.fn().mockResolvedValue(null), writeIfGeneration: vi.fn().mockResolvedValue(false), }; - await new JobSearchCache(storage).search( + await expect(new JobSearchCache(storage).search( parseJobSearchQuery({ family: "product" }), { page: 1, limit: 20 }, null, async () => ({ jobs: [], total: 0 }), - ); + )).rejects.toMatchObject({ statusCode: 503 }); expect((await searchCacheRequests.get()).values).toEqual([ expect.objectContaining({ labels: { result: "stale" }, value: 1 }), ]); diff --git a/backend/tests/unit/middleware/errorHandler.test.ts b/backend/tests/unit/middleware/errorHandler.test.ts index a039809..5009726 100644 --- a/backend/tests/unit/middleware/errorHandler.test.ts +++ b/backend/tests/unit/middleware/errorHandler.test.ts @@ -10,6 +10,13 @@ function createRes() { } describe("errorHandler", () => { + it("serializa indisponibilidade do catálogo como HTTP 503 controlado", () => { + const { status, json, res } = createRes(); + const error = new AppError("SEARCH_CATALOG_UNAVAILABLE", "Catálogo temporariamente indisponível.", 503, { reason: "generation_changed" }); + errorHandler(error, {} as any, res, vi.fn()); + expect(status).toHaveBeenCalledWith(503); + expect(json).toHaveBeenCalledWith(error.toJSON()); + }); it("retorna FORBIDDEN para erro de CORS", () => { const { status, json, res } = createRes(); diff --git a/backend/tests/unit/modules/jobs/jobSearchCache.test.ts b/backend/tests/unit/modules/jobs/jobSearchCache.test.ts index 5e0120c..41dd514 100644 --- a/backend/tests/unit/modules/jobs/jobSearchCache.test.ts +++ b/backend/tests/unit/modules/jobs/jobSearchCache.test.ts @@ -44,8 +44,8 @@ describe("generation-aware search cache", () => { }); it("does not serve an old generation during invalidation", async () => { const storage = store(); - storage.read.mockResolvedValue(page); - storage.generation.mockResolvedValueOnce("1").mockResolvedValueOnce("2"); + storage.read.mockResolvedValueOnce(page).mockResolvedValue(null); + storage.generation.mockResolvedValue("2").mockResolvedValueOnce("1"); const query = vi.fn().mockResolvedValue({ total: 0, jobs: [] }); expect( await new JobSearchCache(storage).search( @@ -57,11 +57,14 @@ describe("generation-aware search cache", () => { ).toEqual({ total: 0, jobs: [] }); expect(query).toHaveBeenCalledOnce(); }); - it("bypasses cache while indexes are unavailable", async () => { + it("returns controlled unavailability while indexes are unavailable", async () => { const storage = store(); storage.generation.mockResolvedValue(null); const query = vi.fn().mockResolvedValue(page); - await new JobSearchCache(storage).search(filters, pagination, null, query); + await expect(new JobSearchCache(storage).search(filters, pagination, null, query)).rejects.toMatchObject({ + code: "SEARCH_CATALOG_UNAVAILABLE", statusCode: 503, details: { reason: "catalog_unavailable" }, + }); + expect(query).not.toHaveBeenCalled(); expect(storage.read).not.toHaveBeenCalled(); expect(storage.writeIfGeneration).not.toHaveBeenCalled(); }); @@ -91,6 +94,85 @@ describe("generation-aware search cache", () => { cache.search(filters, pagination, null, failing), ).resolves.toEqual(page); }); + it("discards a build raced by a new generation and shares one reconstruction", async () => { + const storage = store(); + let generation = "1"; + storage.generation.mockImplementation(async () => generation); + const fresh = { total: 42, jobs: [{ id: "fresh", matchScore: 98 }] }; + const query = vi.fn().mockImplementationOnce(async () => { generation = "2"; return page; }).mockResolvedValue(fresh); + const cache = new JobSearchCache(storage); + const results = await Promise.all([ + cache.search(filters, pagination, { userId: "one" }, query), + cache.search(filters, pagination, { userId: "one" }, query), + ]); + expect(results).toEqual([fresh, fresh]); + expect(query).toHaveBeenCalledTimes(2); + expect(storage.writeIfGeneration).toHaveBeenCalledExactlyOnceWith(expect.any(String), fresh, "2", 120); + results[0].jobs.pop(); + expect(results[1].jobs).toHaveLength(1); + }); + + it.each([true, false])("revalidates after publication returning %s", async (published) => { + const storage = store(); + let generation = "1"; + storage.generation.mockImplementation(async () => generation); + storage.writeIfGeneration.mockImplementationOnce(async () => { generation = "2"; return published; }); + const fresh = { total: 0, jobs: [] }; + const query = vi.fn().mockResolvedValueOnce(page).mockResolvedValue(fresh); + await expect(new JobSearchCache(storage).search(filters, pagination, null, query)).resolves.toEqual(fresh); + expect(query).toHaveBeenCalledTimes(2); + expect(storage.writeIfGeneration).toHaveBeenLastCalledWith(expect.any(String), fresh, "2", 120); + }); + + it("stops after two raced builds and releases single-flight state", async () => { + const storage = store(); + let generation = 1; + storage.generation.mockImplementation(async () => String(generation)); + const query = vi.fn().mockImplementation(async () => { generation++; return page; }); + const cache = new JobSearchCache(storage); + await expect(cache.search(filters, pagination, null, query)).rejects.toMatchObject({ + code: "SEARCH_CATALOG_UNAVAILABLE", statusCode: 503, details: { reason: "generation_changed" }, + }); + expect(query).toHaveBeenCalledTimes(2); + expect(storage.writeIfGeneration).not.toHaveBeenCalled(); + query.mockResolvedValue(page); + await expect(cache.search(filters, pagination, null, query)).resolves.toEqual(page); + }); + + it.each(["unavailable", "read_failed"])("does not return a page when the final fence is %s", async (reason) => { + const storage = store(); + storage.generation.mockResolvedValueOnce("1").mockResolvedValueOnce("1").mockResolvedValueOnce("1"); + if (reason === "unavailable") storage.generation.mockResolvedValue(null); + else storage.generation.mockRejectedValue(new Error("read failed")); + await expect(new JobSearchCache(storage).search(filters, pagination, null, async () => page)).rejects.toMatchObject({ statusCode: 503 }); + }); + + it("rejects repeated publication fencing failures without unlimited retries", async () => { + const storage = store(); + storage.writeIfGeneration.mockResolvedValue(false); + const query = vi.fn().mockResolvedValue(page); + await expect(new JobSearchCache(storage).search(filters, pagination, null, query)).rejects.toMatchObject({ + statusCode: 503, details: { reason: "publication_rejected" }, + }); + expect(query).toHaveBeenCalledTimes(2); + }); + + it("keeps filters, page, ordering and personalized contexts isolated", async () => { + const storage = store(); + const cache = new JobSearchCache(storage); + const combined = parseJobSearchQuery({ family: "backend", technology: "go", type: "remoto", contract: "pj", matchSort: "desc" }); + const selected = { page: 2, limit: 2 }; + const ranked = { total: 9, jobs: [{ id: "a", matchScore: 90 }, { id: "b", matchScore: 80 }] }; + const query = vi.fn().mockResolvedValue(ranked); + await Promise.all([ + cache.search(combined, selected, { userId: "one" }, query), + cache.search(combined, selected, { userId: "two" }, query), + cache.search(combined, { page: 1, limit: 2 }, { userId: "one" }, query), + cache.search({ ...combined, matchSort: "asc" }, selected, { userId: "one" }, query), + ]).then(results => expect(results).toEqual([ranked, ranked, ranked, ranked])); + expect(query).toHaveBeenCalledTimes(4); + expect(new Set(storage.writeIfGeneration.mock.calls.map(([key]) => key)).size).toBe(4); + }); it("tolerates cache read/write outages without hiding query failures", async () => { const storage = store(); storage.read.mockRejectedValue(new Error("cache down")); @@ -111,7 +193,7 @@ describe("generation-aware search cache", () => { null, async () => page, ), - ).resolves.toEqual(page); + ).rejects.toMatchObject({ statusCode: 503, details: { reason: "generation_read_failed" } }); }); it.each([0, -1, 1.5, 86401, NaN])("rejects invalid TTL %s", (ttl) => { expect(() => new JobSearchCache(store(), ttl)).toThrow( From e1a255047ea14675b57e56f62b02ea6c8dbbfd6a Mon Sep 17 00:00:00 2001 From: hltav Date: Fri, 6 Nov 2026 23:31:12 -0300 Subject: [PATCH 4/4] perf(PAV-187): reutiliza filtros preparados na busca --- .../modules/jobs/filters/jobSearch.filter.ts | 14 ++++-- .../jobs/repositories/jobSearch.repository.ts | 8 +++- .../modules/jobs/jobSearch.filter.test.ts | 18 +++++++ .../jobs/jobSearch.preparedFilter.test.ts | 47 +++++++++++++++++++ 4 files changed, 82 insertions(+), 5 deletions(-) create mode 100644 backend/tests/unit/modules/jobs/jobSearch.preparedFilter.test.ts diff --git a/backend/src/modules/jobs/filters/jobSearch.filter.ts b/backend/src/modules/jobs/filters/jobSearch.filter.ts index 74c6eb3..d47ce8b 100644 --- a/backend/src/modules/jobs/filters/jobSearch.filter.ts +++ b/backend/src/modules/jobs/filters/jobSearch.filter.ts @@ -288,6 +288,14 @@ export function filterJobs( jobs: unknown[], filters: ParsedJobSearchQuery, ): unknown[] { + return prepareJobFilter(filters)(jobs); +} + +/** Request-local preparation: reuse normalized filters across hydrated batches. */ +export function prepareJobFilter( + filters: ParsedJobSearchQuery, +): (jobs: unknown[]) => unknown[] { + const familyMode = filters.familyMode; const level = normalizeLevelFilter(filters.level); const seniority = normalizeLevelFilter(filters.seniority); const location = normalizeComparable(filters.country || filters.location); @@ -314,10 +322,10 @@ export function filterJobs( technologies.length === 0 && companies.length === 0 ) { - return jobs; + return (jobs) => jobs; } - return jobs.filter((job) => { + return (jobs) => jobs.filter((job) => { const candidate = job as SearchJob; const title = candidate.title ?? ""; const jobLocation = candidate.location ?? ""; @@ -325,7 +333,7 @@ export function filterJobs( const classification = candidate.classification; const classifiedFamilies = [ classification?.primaryFamily, - ...(filters.familyMode === "any" ? classification?.relatedFamilies ?? [] : []), + ...(familyMode === "any" ? classification?.relatedFamilies ?? [] : []), ] .filter(Boolean) .map((value) => normalizeComparable(String(value))); diff --git a/backend/src/modules/jobs/repositories/jobSearch.repository.ts b/backend/src/modules/jobs/repositories/jobSearch.repository.ts index 422c2a4..77eeb9c 100644 --- a/backend/src/modules/jobs/repositories/jobSearch.repository.ts +++ b/backend/src/modules/jobs/repositories/jobSearch.repository.ts @@ -8,7 +8,7 @@ import { cacheSearchKeywords, } from "../../../lib/cache"; import type { PaginationParams } from "../../../lib/pagination"; -import { filterJobs } from "../filters/jobSearch.filter"; +import { prepareJobFilter } from "../filters/jobSearch.filter"; import type { ParsedJobSearchQuery } from "../types/jobSearch.types"; const BATCH_SIZE = 200; @@ -85,12 +85,16 @@ export class JobSearchRepository { const candidatesMs = clock() - started; let hydrationStarted = clock(); try { + const preparationStarted = clock(); + const applyFilters = prepareJobFilter(filters); + filterMs += clock() - preparationStarted; + hydrationStarted = clock(); for await (const batch of indexed ? indexed.batches() : legacyBatches()) { hydrationMs += clock() - hydrationStarted; batches++; hydratedDocuments += batch.length; const filterStarted = clock(); - const matches = filterJobs(batch, filters); + const matches = applyFilters(batch); filterMs += clock() - filterStarted; matchedDocuments += matches.length; if (filters.matchSort && enrich) { diff --git a/backend/tests/unit/modules/jobs/jobSearch.filter.test.ts b/backend/tests/unit/modules/jobs/jobSearch.filter.test.ts index f2feda5..b10ca54 100644 --- a/backend/tests/unit/modules/jobs/jobSearch.filter.test.ts +++ b/backend/tests/unit/modules/jobs/jobSearch.filter.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { filterJobs, + prepareJobFilter, normalizeComparable, inferJobLocationParts, sortJobsByMatch, @@ -76,6 +77,23 @@ describe("inferJobLocationParts", () => { }); describe("filterJobs", () => { + it("reutiliza filtros preparados entre lotes preservando ordem e documentos", () => { + const apply = prepareJobFilter(filters({ company: "acme", country: "Brasil", family: "backend", technology: "Go", contract: "clt" })); + expect([...apply(JOBS.slice(0, 1)), ...apply(JOBS.slice(1))]).toEqual([JOBS[0]]); + expect(apply(JOBS)).toEqual([JOBS[0]]); + expect(apply([])).toEqual([]); + }); + + it("isola a preparação de mudanças posteriores dos filtros e preserva o caminho sem filtros", () => { + const query = filters({ family: "backend", familyMode: "primary" }); + const apply = prepareJobFilter(query); + query.families.push("frontend"); + query.familyMode = "any"; + const data = [JOBS[0], JOBS[1], { id: "related", classification: { primaryFamily: "leadership", relatedFamilies: ["backend"] } }]; + expect(apply(data)).toEqual([JOBS[0]]); + expect(prepareJobFilter(query)(data)).toEqual(data); + expect(prepareJobFilter(filters({}))(JOBS)).toBe(JOBS); + }); it("preserva fallback textual e precedência do país em filtros combinados", () => { const data = [ { id: "known", company: "Acme", location: "Toronto, Canadá" }, diff --git a/backend/tests/unit/modules/jobs/jobSearch.preparedFilter.test.ts b/backend/tests/unit/modules/jobs/jobSearch.preparedFilter.test.ts new file mode 100644 index 0000000..a0ad41d --- /dev/null +++ b/backend/tests/unit/modules/jobs/jobSearch.preparedFilter.test.ts @@ -0,0 +1,47 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const calls = vi.hoisted(() => ({ apply: vi.fn() })); +vi.mock("../../../../src/modules/jobs/filters/jobSearch.filter", async (original) => { + const filters = await original(); + return { + ...filters, + prepareJobFilter: vi.fn((query) => { + const apply = filters.prepareJobFilter(query); + return (jobs: unknown[]) => { calls.apply(jobs); return apply(jobs); }; + }), + }; +}); +vi.mock("../../../../src/modules/jobs/repositories/valkeyJobSearch.adapter", () => ({ + openIndexedSearch: vi.fn(async () => null), +})); +vi.mock("../../../../src/modules/jobs/cache/valkeySearchCache.adapter", () => ({ + searchPageCache: { search: (_filters: unknown, _page: unknown, _context: unknown, query: () => Promise) => query() }, +})); +vi.mock("../../../../src/lib/cache", () => ({ + cacheAbsoluteSMembers: vi.fn(), cacheGetJobsByIds: vi.fn(), cacheSearchKeywords: vi.fn(), +})); +import { cacheAbsoluteSMembers, cacheGetJobsByIds } from "../../../../src/lib/cache"; +import { filterJobs, prepareJobFilter, sortJobsByMatch } from "../../../../src/modules/jobs/filters/jobSearch.filter"; +import { parseJobSearchQuery } from "../../../../src/modules/jobs/parsers/jobSearchQuery.parser"; +import { JobSearchRepository } from "../../../../src/modules/jobs/repositories/jobSearch.repository"; + +beforeEach(() => vi.clearAllMocks()); + +describe("preparação única dos filtros na busca fria", () => { + it.each([null, "asc", "desc"] as const)("preserva filtros residuais, total e página com Match %s", async (direction) => { + const data = Array.from({ length: 405 }, (_, index) => ({ + id: String(index), company: index % 3 === 0 ? "Acme" : "Outra", + modality: index % 2 === 0 ? "Remote" : "Onsite", matchScore: index % 7, + classification: { primaryFamily: "backend", technologies: ["Go"] }, + })); + vi.mocked(cacheAbsoluteSMembers).mockResolvedValue(data.map(job => job.id)); + vi.mocked(cacheGetJobsByIds).mockImplementation(async ids => ids.flatMap(id => data.filter(job => job.id === id))); + const query = parseJobSearchQuery({ company: "Acme", type: "remoto", family: "backend", technology: "Go", ...(direction ? { matchSort: direction } : {}) }); + const matching = filterJobs(data, query); + const expected = direction ? sortJobsByMatch(matching, direction) : matching; + const page = await new JobSearchRepository().search(query, { page: 2, limit: 4 }, direction ? async jobs => jobs : undefined); + expect(page).toEqual({ jobs: expected.slice(4, 8), total: expected.length }); + expect(prepareJobFilter).toHaveBeenCalledExactlyOnceWith(query); + expect(calls.apply.mock.calls.map(([batch]) => batch.length)).toEqual([200, 200, 5]); + }); +});