From d5a7271ddde581fc49622503b250918d4e80579e Mon Sep 17 00:00:00 2001 From: paula-alves Date: Fri, 6 Nov 2026 22:29:10 +0000 Subject: [PATCH 1/2] fix(faces,autopilot): align crop-scale tests with linear semantics, fix dead vote gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The crop-geometry refactor moved the area→linear sqrt conversion into cropBiasOf but left two learning.ts test expectations on the old area-ratio values, and a FoldedCrop.x0/.x1/.y0/.y1 access that no longer exists now that FoldedCrop is { rect, angle } (silently NaN -> null through the JSON round-trip, collapsing the learnt crop factor to null). In faces/service.ts, the conflicting-number score penalty required read.votes >= 2, but majorityNumber() already only returns a result once it has a real majority -- for a single-face group votes is always 1, so the penalty could never fire. --- apps/api/src/faces/service.ts | 2 +- apps/api/test/autopilot.test.ts | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/apps/api/src/faces/service.ts b/apps/api/src/faces/service.ts index 613dfa1..d002023 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -621,7 +621,7 @@ export class FaceService { const onTeam = team ? await this.playersOfTeam([first.p], team.teamId) : null; if (team && onTeam?.has(first.p.id)) suggestionScore = faceNumberKitScore(first.s, read.score, team.sure); else suggestionScore = faceAndNumberScore(first.s, read.score); - } else if (read && firstNumber && firstNumber !== read.number && read.votes >= 2) { + } else if (read && firstNumber && firstNumber !== read.number) { suggestionScore = Math.round(first.s * 0.8 * 1000) / 1000; } } else if (read && allowNumber) { diff --git a/apps/api/test/autopilot.test.ts b/apps/api/test/autopilot.test.ts index c1c0224..f0891e8 100644 --- a/apps/api/test/autopilot.test.ts +++ b/apps/api/test/autopilot.test.ts @@ -135,8 +135,9 @@ describe("learning from corrections", () => { expect(c?.deltas["light.exposure"]).toBe(0.35); expect(c?.deltas["light.shadows"]).toBe(12); expect(c?.deltas["wb.temp"]).toBe(300); - expect(c?.cropScale).toBeCloseTo(0.75, 2); - expect(c?.cropBias?.scale).toBeCloseTo(0.75, 2); + // Scale is linear (cropBias.ts): the crop only narrows in x here, so it is the geometric mean of the two axes. + expect(c?.cropScale).toBeCloseTo(0.866, 2); + expect(c?.cropBias?.scale).toBeCloseTo(0.866, 2); // A reset is "less of everything the autopilot did" for tone; white balance says nothing then. expect(correctionOf(auto, fold([set({ "light.exposure": 0.2, "wb.temp": 5200 }), { command: "develop.reset" }]))).toEqual({ deltas: { "light.exposure": -0.2 }, @@ -151,7 +152,8 @@ describe("learning from corrections", () => { const rows = [0.3, 0.25, 0.35, 0.3, -0.1].map((e, i) => ({ deltas: { "light.exposure": e, "light.contrast": i % 2 ? 8 : -8 }, cropScale: 0.7 })); const style = styleOf(rows, null); expect(style.offsets).toEqual({ "light.exposure": 0.3 }); - expect(style.cropFactor).toBeCloseTo(0.7, 2); + // 0.7 is below the 0.75 floor (never suggest tighter than that), so it saturates there. + expect(style.cropFactor).toBeCloseTo(0.75, 2); expect(styleOf(rows.slice(0, 4), null).offsets).toEqual({}); const open = [1.1, 1.12, 1.08, 1.15, 1.09].map((s) => ({ deltas: { "__crop.scale": s, "__crop.dx": 0.02, "__crop.dy": -0.03, "__crop.dAngle": 0 }, @@ -394,7 +396,7 @@ describe("autopilot", () => { // The photographer lifts the exposure (0.2 -> 0.5) and crops tighter on five of them. for (const id of photos.slice(0, 5)) { const auto = fold((await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } })).map((e) => e.command as never)); - const r = auto.crop!; + const r = auto.crop!.rect; const shrink = (a: number, b: number) => [a + (b - a) * 0.08, b - (b - a) * 0.08] as const; const [x0, x1] = shrink(r.x0, r.x1); const [y0, y1] = shrink(r.y0, r.y1); @@ -412,8 +414,8 @@ describe("autopilot", () => { await autopilot.decideBursts(new Date(Date.now() + 20_000)); const edits = await ctx.db.photoEdit.findMany({ where: { photoId: next }, orderBy: { seq: "asc" } }); expect((edits[0]!.command as { params: { values: Record } }).params.values).toEqual({ "light.exposure": 0.5, "light.contrast": 10 }); - const before = fold((await ctx.db.photoEdit.findMany({ where: { photoId: photos[5]! }, orderBy: { seq: "asc" } })).map((e) => e.command as never)).crop!; - const after = fold(edits.map((e) => e.command as never)).crop!; + const before = fold((await ctx.db.photoEdit.findMany({ where: { photoId: photos[5]! }, orderBy: { seq: "asc" } })).map((e) => e.command as never)).crop!.rect; + const after = fold(edits.map((e) => e.command as never)).crop!.rect; expect(after.x1 - after.x0).toBeLessThan(before.x1 - before.x0); expect(((await ctx.db.photo.findUniqueOrThrow({ where: { id: next } })).autopilot as { style: { samples: number } }).style.samples).toBe(5); -- 2.47.3 From e108c12d2b59501cea94090c866157070979aa5a Mon Sep 17 00:00:00 2001 From: paula-alves Date: Fri, 6 Nov 2026 22:49:52 +0000 Subject: [PATCH 2/2] fix(sports): wire a signer into SportsService and stamp the M19 friendlies' lastIngestAt (BIT-32085) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit facesOf() called storage.personUrl(), but signed URLs live on UrlSigner, not LocalStorage — a typecheck break that blocks ci/typescript on every PR. Threaded SportsDeps.signer through app.ts, worker.ts and the tests that construct SportsService directly. saveM19Friendlies()'s upsert never set lastIngestAt, so refreshDue() saw the FPA group as always due and refetched everything on every call instead of respecting the six-hour cache. Also updates two sports.test.ts assertions (15 vs 16 competitions, and externalId 228107's shirt number) that were written before the M19-AMIG youth friendlies and verified Caminha match-report numbers landed. --- apps/api/src/app.ts | 2 +- apps/api/src/sports/service.ts | 13 +++++++------ apps/api/src/worker.ts | 2 +- apps/api/test/sports.test.ts | 12 ++++++++---- 4 files changed, 17 insertions(+), 12 deletions(-) diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index a30e309..a04ab67 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -110,7 +110,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give : (realtime ?? silentBroadcaster); app.addHook("onClose", async () => broadcaster.close()); const secrets = config.DELIVERY_SECRET_KEY ? new SecretBox(config.DELIVERY_SECRET_KEY) : undefined; - const sports = new SportsService({ db, storage, log: app.log, fetch: fetchImpl ?? fetch }); + const sports = new SportsService({ db, storage, signer, log: app.log, fetch: fetchImpl ?? fetch }); // Archive clouds: the API connects them, matches galleries and streams originals; the worker walks and indexes. const archive = new ArchiveService({ db, secrets, log: app.log, syncSquads: (id) => sports.syncEventSquads(id), ligaSeason: (season) => sports.importLigaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, storage, ...(fetchImpl && { fetchImpl }) }); const delivery = new DeliveryService({ db, storage, secrets, broadcaster, log: app.log, originals: archive, ...(fetchImpl && { fetchImpl }) }); diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 8de08bc..3248265 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -8,7 +8,7 @@ import type { IngestLogger } from "../ingest/service.js"; import { DEFAULT_CODE_LIST } from "../library/iptc.js"; import { badRequest, notFound } from "../lib/errors.js"; import { waitUntil } from "../lib/idle.js"; -import type { LocalStorage } from "../storage/storage.js"; +import type { LocalStorage, UrlSigner } from "../storage/storage.js"; import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js"; import { fetchYouthCamps, youthAbbrev } from "./fpa-youth.js"; import { samePlayer } from "./identity.js"; @@ -98,6 +98,7 @@ const SPORT: Record = { LIGA: "futebol", FPF: "futebol", export interface SportsDeps { db: Db; storage: LocalStorage; + signer: UrlSigner; log: IngestLogger; fetch: Fetch; /** Pause between FPF pages (be gentle with the site). */ @@ -558,7 +559,7 @@ export class SportsService { result.players += await this.saveNationalCallUp(snamId, season, SNAM_EURO_CUP_2026); result.players += await this.saveNationalCallUp(suiId, season, SUI_EURO_CUP_2026); // The calendar first. Reading the call-up PDFs takes minutes and must not hide tonight's game. - result.fixtures += await this.saveM19Friendlies(season); + result.fixtures += await this.saveM19Friendlies(season, now); // The federation's recent youth posts (PDF + calendar). The November M19 list below is only the // first seed, so a later camp is not put back to this one when the site is briefly down. const youth = await this.importFpaYouth(season, result); @@ -576,12 +577,12 @@ export class SportsService { } /** The two Portugal–Spain under-19 friendlies (Caminha 5 Nov, Salceda 7 Nov 2026). Picking the fixture links the plantel. */ - private async saveM19Friendlies(season: string): Promise { + private async saveM19Friendlies(season: string, now: Date): Promise { const { db } = this.deps; const comp = await db.sportsCompetition.upsert({ where: { provider_externalId: { provider: "FPA", externalId: "M19-AMIG" } }, - create: { provider: "FPA", externalId: "M19-AMIG", sport: "andebol", name: "Sub-19 masculina", gender: "M", season }, - update: { name: "Sub-19 masculina", season }, + create: { provider: "FPA", externalId: "M19-AMIG", sport: "andebol", name: "Sub-19 masculina", gender: "M", season, lastIngestAt: now }, + update: { name: "Sub-19 masculina", season, lastIngestAt: now }, }); const por = NATIONAL_SIDES.find((s) => s.externalId === "M19"); const esp = NATIONAL_SIDES.find((s) => s.externalId === "ESP-M19"); @@ -1780,7 +1781,7 @@ export class SportsService { where: { id: { in: ids }, referenceKey: { not: null } }, select: { id: true }, }); - for (const person of people) out.set(person.id, this.deps.storage.personUrl(person.id)); + for (const person of people) out.set(person.id, this.deps.signer.personUrl(person.id)); return out; } diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index 8ced311..d3e94ac 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -103,7 +103,7 @@ if (!renderEngine) log.warn("RENDER_BIN not set: edited photos get no new thumbn const develop = new DevelopService({ db, storage, signer, broadcaster, log, engine: renderEngine }); const renders = renderEngine ? new RenderWorker(develop, { concurrency: capacity.render, intervalMs: 500, log }) : undefined; -const sportsService = new SportsService({ db, storage, log, fetch }); +const sportsService = new SportsService({ db, storage, signer, log, fetch }); // Archive clouds: walked for new galleries, each image indexed as a preview whose original stays in the cloud. // A big backlog: many downloads from the cloud in flight, previews made by as many as the machine's share. const videoTools = findVideoTools({ ffmpeg: config.FFMPEG_BIN, ffprobe: config.FFPROBE_BIN }, homedir()); diff --git a/apps/api/test/sports.test.ts b/apps/api/test/sports.test.ts index 1bf7a35..f5c91f7 100644 --- a/apps/api/test/sports.test.ts +++ b/apps/api/test/sports.test.ts @@ -7,7 +7,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { BLOCK_START, buildCodeLines, mergeGenerated, teamPrefix, toTsv } from "../src/sports/codegen.js"; import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js"; import { SportsService } from "../src/sports/service.js"; -import { LocalStorage } from "../src/storage/storage.js"; +import { LocalStorage, UrlSigner } from "../src/storage/storage.js"; import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; const quiet = { info: () => {}, warn: () => {} }; @@ -349,7 +349,7 @@ describe("sports data service", () => { sites = fakeSites(state); ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage") }, undefined, sites.fetcher as unknown as typeof fetch); state.png = await sharp({ create: { width: 200, height: 200, channels: 4, background: { r: 200, g: 0, b: 0, alpha: 0.5 } } }).png().toBuffer(); - sports = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), log: quiet, fetch: sites.fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 }); + sports = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), signer: new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC), log: quiet, fetch: sites.fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 }); }); afterAll(async () => { await ctx.app.close(); @@ -383,6 +383,7 @@ describe("sports data service", () => { ["EHF", "el-women", "20262027"], ["LIGA", "ligaportugalbetclic", "20262027"], ["LIGA", "ligaportugalmeusuper", "20262027"], + ["FPA", "M19-AMIG", "20262027"], ["UEFA", "1", "20262027"], ["UEFA", "2019", "20262027"], ["UEFA", "14", "20262027"], @@ -395,6 +396,8 @@ describe("sports data service", () => { ["MADEIRA SAD", "ABC DE BRAGA", "2026-10-14T18:30:00.000Z"], ["Torreense", "Sunderland", "2026-10-15T16:45:00.000Z"], ["SL Benfica", "FC Porto", "2026-10-18T19:30:00.000Z"], + ["Portugal", "Espanha", "2026-11-05T20:00:00.000Z"], + ["Espanha", "Portugal", "2026-11-07T17:30:00.000Z"], ]); const benfica = await ctx.db.sportsTeam.findFirstOrThrow({ where: { name: "SL Benfica" } }); expect((await sports.squad(benfica.id)).map((p) => [p.number, p.name])).toEqual([ @@ -669,7 +672,7 @@ describe("sports data service", () => { if (u.pathname.endsWith("/141/373/4")) return json([{ ...fpaGame("900002", "2026-03-07", AGUAS, GIL, [25, 27]), ID_ASSOCIACAO: "8" }, regional]) as never; return json([]) as never; }; - const service = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), log: quiet, fetch: fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 }); + const service = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), signer: new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC), log: quiet, fetch: fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 }); expect(await service.importFpaSeason("20252026")).toBe(2); const saved = await ctx.db.sportsFixture.findMany({ where: { season: "20252026", externalId: { in: ["900001", "900002", "900003"] } }, select: { externalId: true } }); expect(saved.map((f) => f.externalId).sort()).toEqual(["900001", "900002"]); @@ -723,6 +726,7 @@ describe("sports data service", () => { sports = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), + signer: new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC), log: quiet, fetch: (async (url, init) => { const u = String(url); @@ -826,7 +830,7 @@ describe("sports data service", () => { const m19 = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "FPA", externalId: "M19" } }); expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: m19.id, name: "Santiago Póvoas" } })).toMatchObject({ externalId: "228107", - number: null, + number: "12", }); expect(await ctx.db.sportsPlayer.count({ where: { teamId: m19.id, goneAt: null } })).toBe(22); const espM19 = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "FPA", externalId: "ESP-M19" } }); -- 2.47.3