diff --git a/apps/api/src/autopilot/curate.ts b/apps/api/src/autopilot/curate.ts index 560f05f..745977d 100644 --- a/apps/api/src/autopilot/curate.ts +++ b/apps/api/src/autopilot/curate.ts @@ -79,12 +79,16 @@ export function galleryCeiling(count: number): number { * Decides the windows that have closed and are not decided yet. `decided` holds the candidates already decided * (chosen or not), so earlier choices count against the gallery size. */ -export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean }[], opts: CurateOptions): WindowDecision[] { +export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean; at?: number }[], opts: CurateOptions): WindowDecision[] { const windowMs = opts.windowMs ?? 5 * 60_000; const minGapMs = opts.minGapMs ?? 5_000; const settleMs = opts.settleMs ?? 60_000; const done = new Map(decided.map((d) => [d.id, d.chosen])); - let chosenSoFar = [...done.values()].filter(Boolean).length; + // Choices already made. When each one carries its capture time, it only fills the windows up to its own, + // so a later send does not eat the share of an earlier window that was skipped. + const priorChosen = decided.filter((d) => d.chosen); + const priorUntimed = priorChosen.filter((d) => d.at === undefined).length; + let chosenThisPass = 0; const cap = galleryCeiling(opts.count); const perWindow = (opts.count * windowMs) / opts.durationMs; const windows = Math.max(1, opts.durationMs / windowMs); @@ -111,6 +115,7 @@ export function curate(candidates: Candidate[], decided: { id: string; chosen: b const end = opts.start + (w + 1) * windowMs; if (end + settleMs > opts.now) break; // The share up to the end of this window, minus what was already chosen; at most three windows' worth at once. + const chosenSoFar = priorUntimed + priorChosen.filter((d) => d.at !== undefined && d.at < end).length + chosenThisPass; const target = Math.min(opts.count, Math.round(perWindow * (w + 1))); const room = Math.max(0, Math.min(target - chosenSoFar, Math.ceil(3 * perWindow), opts.count - chosenSoFar)); const ranked = list.filter((x) => x.s > 0 && x.s >= floor).sort((a, b) => b.s - a.s); @@ -134,7 +139,7 @@ export function curate(candidates: Candidate[], decided: { id: string; chosen: b extraLeft -= 1; } } - chosenSoFar += chosen.length; + chosenThisPass += chosen.length; out.push({ window: w, ids: list.map((x) => x.c.id), chosen: chosen.sort((a, b) => a.at - b.at).map((c) => c.id) }); } return out; diff --git a/apps/api/src/autopilot/service.ts b/apps/api/src/autopilot/service.ts index 94cab91..3f9a1c2 100644 --- a/apps/api/src/autopilot/service.ts +++ b/apps/api/src/autopilot/service.ts @@ -374,7 +374,7 @@ export class AutopilotService { const ranked = photos.filter((p) => (p.autopilot as unknown as AutopilotRecord | null)?.hold !== "ball").map((p) => ({ ...p, look: look.get(p.id) ?? 1 })); const decided = photos .filter((p) => (p.autopilot as unknown as AutopilotRecord | null)?.curated) - .map((p) => ({ id: p.id, chosen: !!(p.autopilot as unknown as AutopilotRecord).chosen })); + .map((p) => ({ id: p.id, chosen: !!(p.autopilot as unknown as AutopilotRecord).chosen, at: p.capturedAt?.getTime() ?? 0 })); const targets = exportTargets(settings); const galleries = settings.galleries ?? []; // With 2+ exports, curate on the best frame; delivery below assigns best/2nd/… to each target. @@ -405,7 +405,7 @@ export class AutopilotService { if (g.count === max) continue; const earlier = photos.flatMap((p) => { const flag = (p.autopilot as unknown as AutopilotRecord | null)?.gallery?.[g.targetId]; - return flag === undefined ? [] : [{ id: p.id, chosen: flag }]; + return flag === undefined ? [] : [{ id: p.id, chosen: flag, at: p.capturedAt?.getTime() ?? 0 }]; }); const parts = curate(candidates, earlier, { count: g.count, ...curateOpts }); chosenBy.set(g.targetId, new Set(parts.flatMap((d) => d.chosen))); diff --git a/apps/api/src/ingest/exif.ts b/apps/api/src/ingest/exif.ts index c1f5149..9ee9f05 100644 --- a/apps/api/src/ingest/exif.ts +++ b/apps/api/src/ingest/exif.ts @@ -94,6 +94,7 @@ export function withCameraRatingChecked(exif: unknown): Record } const CAPTURE_CLOCK_CHECKED = "captureClockChecked"; +const CAPTURE_CLOCK_RECURATE = "captureClockRecurate"; /** Marks a photo whose capture time was compared again with the file, so the winter-offset repair does not repeat. */ export function withCaptureClockChecked(exif: unknown): Record { @@ -101,6 +102,12 @@ export function withCaptureClockChecked(exif: unknown): Record return { ...base, [CAPTURE_CLOCK_CHECKED]: true }; } +/** One fresh gallery decision after the clock moved, so a frame skipped as warm-up can still be sent. */ +export function withCaptureClockRecurate(exif: unknown): Record { + const base = exif && typeof exif === "object" && !Array.isArray(exif) ? { ...(exif as Record) } : {}; + return { ...base, [CAPTURE_CLOCK_RECURATE]: true }; +} + const TIME_ZONE = "Europe/Lisbon"; /** Offset of a time zone at a given UTC instant, in minutes (Lisbon: 0 in winter, 60 in summer). */ diff --git a/apps/api/src/ingest/service.ts b/apps/api/src/ingest/service.ts index 8a15d98..49c6b66 100644 --- a/apps/api/src/ingest/service.ts +++ b/apps/api/src/ingest/service.ts @@ -9,7 +9,7 @@ import { stripNulBytes } from "../lib/sanitize.js"; import type { Broadcaster } from "../realtime.js"; import { LocalStorage, sha256File, UrlSigner, VARIANT_SIZE } from "../storage/storage.js"; import { readEmbeddedIptc } from "./embedded.js"; -import { cullFromCameraRating, readCameraInfo, withCameraRatingChecked, withCaptureClockChecked } from "./exif.js"; +import { cullFromCameraRating, readCameraInfo, withCameraRatingChecked, withCaptureClockChecked, withCaptureClockRecurate } from "./exif.js"; import { jpegFileComplete } from "./jpeg.js"; export const ACCEPTED_EXTENSIONS = new Set([".jpg", ".jpeg"]); @@ -550,6 +550,40 @@ export class IngestService { return fixed; } + /** + * Frames the autopilot skipped while their clock was an hour early. One fresh decision, with the corrected + * time, so the share of the match they belong to can still go out. + */ + async recurateAfterClockRepair(limit = 200): Promise { + const { db, log } = this.deps; + const rows = await db.$queryRaw>` + SELECT id, exif, autopilot + FROM photos + WHERE created_at > now() - interval '3 days' + AND COALESCE((exif::jsonb->>'captureClockChecked')::boolean, false) IS TRUE + AND COALESCE((exif::jsonb->>'captureClockRecurate')::boolean, false) IS NOT TRUE + AND (autopilot->>'curated') = 'true' + AND COALESCE((autopilot->>'chosen')::boolean, false) IS NOT TRUE + ORDER BY captured_at ASC + LIMIT ${limit} + `; + for (const row of rows) { + const autopilot = row.autopilot && typeof row.autopilot === "object" && !Array.isArray(row.autopilot) ? { ...(row.autopilot as Record) } : {}; + delete autopilot.curated; + delete autopilot.chosen; + delete autopilot.gallery; + await db.photo.update({ + where: { id: row.id }, + data: { + exif: withCaptureClockRecurate(row.exif) as Prisma.InputJsonValue, + autopilot: autopilot as Prisma.InputJsonValue, + }, + }); + } + if (rows.length) log.info({ photos: rows.length }, "ingest: gallery decision reopened after the clock repair"); + return rows.length; + } + private async makeDerivatives(orgId: string, sha256: string, storageKey: string): Promise<{ width: number; height: number }> { const { storage } = this.deps; const source = storage.resolve(storageKey); diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index b1915a5..7cf049b 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -187,9 +187,11 @@ invoices.start(); const ratingBackfill = setInterval(() => { void ingest.backfillCameraRatings(25).catch((err) => log.warn({ err }, "ingest: camera rating backfill failed")); void ingest.backfillCaptureClock(100).catch((err) => log.warn({ err }, "ingest: capture clock repair failed")); + void ingest.recurateAfterClockRepair(200).catch((err) => log.warn({ err }, "ingest: gallery reopen after clock repair failed")); }, 60_000); void ingest.backfillCameraRatings(25).catch((err) => log.warn({ err }, "ingest: camera rating backfill failed")); void ingest.backfillCaptureClock(100).catch((err) => log.warn({ err }, "ingest: capture clock repair failed")); +void ingest.recurateAfterClockRepair(200).catch((err) => log.warn({ err }, "ingest: gallery reopen after clock repair failed")); log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started"); /** Drain in-flight jobs before ending the Prisma/pg pool (BIT-31189). Leave headroom under PM2 kill_timeout. */ diff --git a/apps/api/test/autopilot.test.ts b/apps/api/test/autopilot.test.ts index f6c933c..806577d 100644 --- a/apps/api/test/autopilot.test.ts +++ b/apps/api/test/autopilot.test.ts @@ -125,6 +125,14 @@ describe("only the best", () => { const live = decided.filter((d) => d.chosen).length; expect(Math.abs(live - all.length)).toBeLessThanOrEqual(2); }); + + it("still fills an earlier window when a later frame was already sent", () => { + const early = [0, 1, 2, 3].map((i) => c(i * 30_000, 5)); + const late = c(10 * min, 5); + const opts = { count: 30, start, durationMs: 105 * min, now: start + 20 * min }; + const opened = curate([...early, late], [{ id: late.id, chosen: true, at: late.at }], opts); + expect(opened.find((d) => d.window === 0)?.chosen.length).toBeGreaterThan(0); + }); }); describe("learning from corrections", () => {