From ce3668ab3ee88ff86ba1f6d515a60d08272f6cd7 Mon Sep 17 00:00:00 2001 From: jackshim415 Date: Thu, 19 Nov 2026 08:09:02 -0800 Subject: [PATCH 1/2] Batch worker imports into finite database execution windows Snapshot due jobs once, preserve leases and retries, and disconnect after draining. Move API maintenance into the worker and finalize archived imports so scheduled offseason windows can finish. Keep continuous event mode as the default until Railway preview sleep and cold-start gates are verified. --- .railway/README.md | 5 + .railway/config.test.mjs | 33 +++- .railway/railway.ts | 16 +- apps/server/src/lib/scheduleJobs.ts | 64 +------- apps/server/test/scheduleJobs.unit.test.ts | 155 +----------------- apps/worker/README.md | 40 ++++- apps/worker/index.ts | 31 ++-- apps/worker/package.json | 1 + apps/worker/src/jobs/maintenance.ts | 28 ++++ apps/worker/src/schedule.ts | 4 +- apps/worker/src/scheduler.ts | 110 +++++++++++-- apps/worker/src/worker.ts | 64 ++++++++ apps/worker/test/batch.test.ts | 85 ++++++++++ .../test/maintenance.integration.test.ts | 112 +++++++++++++ apps/worker/test/schedule.test.ts | 2 +- .../worker/test/scheduler.integration.test.ts | 55 +++++++ apps/worker/test/tournament-schedule.test.ts | 32 ++++ docs/worker-batch-rollout.md | 118 +++++++++++++ 18 files changed, 705 insertions(+), 250 deletions(-) create mode 100644 apps/worker/src/jobs/maintenance.ts create mode 100644 apps/worker/test/batch.test.ts create mode 100644 apps/worker/test/maintenance.integration.test.ts create mode 100644 docs/worker-batch-rollout.md diff --git a/.railway/README.md b/.railway/README.md index d9526137a..1c8533158 100644 --- a/.railway/README.md +++ b/.railway/README.md @@ -75,3 +75,8 @@ API retains the private database migration/start command and staging's 2 CPU / `bun run enqueue tournaments 2025` or `bun run backfill 1992 2025`. See [Railway's IaC migration guide](https://docs.railway.com/infrastructure-as-code#migrating-from-config-as-code). + +For finite offseason batches, see [Worker batch rollout](../docs/worker-batch-rollout.md). +`RAILWAY_WORKER_CRON='0 18 * * *'` is an opt-in local plan/apply input; omitting +it keeps/restores continuous mode. Merging this configuration does not enable +Cron or PostgreSQL Serverless. diff --git a/.railway/config.test.mjs b/.railway/config.test.mjs index b9b5e430d..fa36c10de 100644 --- a/.railway/config.test.mjs +++ b/.railway/config.test.mjs @@ -34,8 +34,13 @@ for (const environment of ["production", "staging"]) { : "offseason/mock-game-charged-up", ); assert(Object.keys(resource.variables).length > 0); - for (const value of Object.values(resource.variables)) { - assert.deepEqual(value, { type: "preserve" }); + for (const [name, value] of Object.entries(resource.variables)) { + assert.deepEqual( + value, + resource.name === "worker" && name === "WORKER_MODE" + ? { type: "literal", value: "continuous" } + : { type: "preserve" }, + ); } } const api = service("api"); @@ -89,3 +94,27 @@ test("refuses preview plans without an explicit source branch", () => { else process.env.RAILWAY_CONFIG_BRANCH = previous; } }); + +test("offseason cron uses a finite batch without a health listener or restarts", () => { + const previous = process.env.RAILWAY_WORKER_CRON; + process.env.RAILWAY_WORKER_CRON = "0 18 * * *"; + try { + const graph = config(createRailwayContext({ environment: "production" })); + const worker = graph.resources.find((r) => r.name === "worker"); + assert.deepEqual(worker.variables.WORKER_MODE, { + type: "literal", + value: "batch", + }); + assert.equal(worker.deploy.cronSchedule, "0 18 * * *"); + assert.equal(worker.deploy.restartPolicyType, "NEVER"); + assert.equal(worker.deploy.healthcheckPath, undefined); + } finally { + if (previous === undefined) delete process.env.RAILWAY_WORKER_CRON; + else process.env.RAILWAY_WORKER_CRON = previous; + } + const worker = config( + createRailwayContext({ environment: "production" }), + ).resources.find((r) => r.name === "worker"); + assert.equal(worker.deploy.cronSchedule, undefined); + assert.equal(worker.deploy.healthcheckPath, "/health"); +}); diff --git a/.railway/railway.ts b/.railway/railway.ts index 56de54855..43cfe2d19 100644 --- a/.railway/railway.ts +++ b/.railway/railway.ts @@ -141,9 +141,14 @@ export default defineRailway((ctx) => { }, }); + // Opt in only after preview validation; merging keeps the current service running. + const workerCron = process.env.RAILWAY_WORKER_CRON?.trim(); const worker = service("worker", { source: source("/"), - env: keep("DATABASE_URL", "TBA_KEY", "WORKER_CONCURRENCY"), + env: { + ...keep("DATABASE_URL", "TBA_KEY", "WORKER_CONCURRENCY"), + WORKER_MODE: workerCron ? "batch" : "continuous", + }, build: { builder: "DOCKERFILE", dockerfilePath: "apps/worker/Dockerfile", @@ -152,8 +157,13 @@ export default defineRailway((ctx) => { deploy: { runtime: "V2", startCommand: "bun index.ts", - healthcheckPath: "/health", - healthcheckTimeout: 120, + ...(workerCron + ? { cronSchedule: workerCron, restartPolicyType: "NEVER" as const } + : { + cronSchedule: null, + healthcheckPath: "/health", + healthcheckTimeout: 120, + }), drainingSeconds: 60, multiRegionConfig: { "us-west2": { diff --git a/apps/server/src/lib/scheduleJobs.ts b/apps/server/src/lib/scheduleJobs.ts index dffcaaeb4..486ff452e 100644 --- a/apps/server/src/lib/scheduleJobs.ts +++ b/apps/server/src/lib/scheduleJobs.ts @@ -1,64 +1,4 @@ -import fetchTeams from "./fetchTeams.js"; -import fetchMatches from "./fetchMatches.js"; -import prisma from "../prismaClient.js"; -import expireReportsInProgress from "./expireReportsInProgress.js"; -import deleteOldRequests from "./deleteOldRequests.js"; -import { runBackgroundTask } from "./errors.js"; - +/** Imports and maintenance belong to the durable Worker queue. */ export default async function scheduleJobs(): Promise { - const skipTba = - process.env.NODE_ENV === "development" && !process.env.TBA_KEY?.trim(); - - if (skipTba) { - console.log("Skipping TBA background jobs: set TBA_KEY to enable imports."); - } else { - // Prevent unnecessary fetching in dev mode which is frequently restarted - if ( - process.env.NODE_ENV === "development" && - (await prisma.team.count()) > 0 - ) { - console.log("Skipping initial TBA data fetch"); - } else { - // Import teams - console.log("Fetching teams from TBA..."); - await fetchTeams(); - console.log("Done fetching teams from TBA."); - } - - // repeat every 24 hours - setInterval( - () => - runBackgroundTask(async () => { - console.log("Fetching teams from TBA..."); - await fetchTeams(); - console.log("Done fetching teams from TBA."); - }, "TBA daily refresh failed"), - 1000 * 60 * 60 * 24, - ); - - //repeat hourly - setInterval( - () => - runBackgroundTask(async () => { - await fetchMatches(); - console.log("Done fetching matches from TBA."); - }, "TBA match refresh failed"), - 1000 * 60 * 60, - ); - } - - // repeat every 12 hours - setInterval( - async () => { - await runBackgroundTask(async () => { - await deleteOldRequests(); - console.log("Done deleting old requests."); - }, "Old request cleanup failed"); - await runBackgroundTask( - expireReportsInProgress, - "Report draft cleanup failed", - ); - }, - 1000 * 60 * 60 * 12, - ); + // Retain the startup hook for consumers; never start API-owned DB timers. } diff --git a/apps/server/test/scheduleJobs.unit.test.ts b/apps/server/test/scheduleJobs.unit.test.ts index 88bbdf9ac..c2d5bf371 100644 --- a/apps/server/test/scheduleJobs.unit.test.ts +++ b/apps/server/test/scheduleJobs.unit.test.ts @@ -1,149 +1,12 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -vi.mock("../src/lib/fetchTeams.js", () => ({ default: vi.fn() })); -vi.mock("../src/lib/fetchMatches.js", () => ({ default: vi.fn() })); -vi.mock("../src/lib/expireReportsInProgress.js", () => ({ - default: vi.fn().mockResolvedValue(undefined), -})); -vi.mock("../src/lib/deleteOldRequests.js", () => ({ default: vi.fn() })); -vi.mock("../src/prismaClient.js", () => ({ - default: { - team: { count: vi.fn().mockResolvedValue(0) }, - }, -})); - -import prisma from "../src/prismaClient.js"; +import { expect, test, vi } from "vitest"; import scheduleJobs from "../src/lib/scheduleJobs.js"; -import fetchTeams from "../src/lib/fetchTeams.js"; -import fetchMatches from "../src/lib/fetchMatches.js"; -import expireReportsInProgress from "../src/lib/expireReportsInProgress.js"; -import deleteOldRequests from "../src/lib/deleteOldRequests.js"; - -describe("background jobs at startup", () => { - beforeEach(() => { - vi.useFakeTimers(); - vi.clearAllMocks(); - vi.mocked(prisma.team.count).mockResolvedValue(0); - vi.stubEnv("NODE_ENV", "development"); - vi.stubEnv("TBA_KEY", ""); - vi.spyOn(console, "log").mockImplementation(() => undefined); - }); - - afterEach(() => { - vi.clearAllTimers(); - vi.useRealTimers(); - vi.unstubAllEnvs(); - vi.restoreAllMocks(); - }); - - it("starts without a TBA key and keeps local cleanup running", async () => { - await scheduleJobs(); - await vi.advanceTimersByTimeAsync(24 * 60 * 60 * 1000); - expect(fetchTeams).not.toHaveBeenCalled(); - expect(fetchMatches).not.toHaveBeenCalled(); - expect(deleteOldRequests).toHaveBeenCalledTimes(2); - expect(expireReportsInProgress).toHaveBeenCalledTimes(2); - }); - it("logs draft cleanup failures without stopping the scheduled job", async () => { - const error = new Error("database unavailable"); - vi.spyOn(console, "error").mockImplementation(() => undefined); - vi.mocked(expireReportsInProgress).mockRejectedValueOnce(error); - await scheduleJobs(); - await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000); - expect(console.error).toHaveBeenCalledWith( - "Report draft cleanup failed", - expect.objectContaining({ name: "Error" }), - ); - expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain( - error.message, - ); - expect(deleteOldRequests).toHaveBeenCalledTimes(1); - await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000); - expect(expireReportsInProgress).toHaveBeenCalledTimes(2); - }); - - it("imports and refreshes TBA data when development has a key", async () => { - vi.stubEnv("TBA_KEY", "synthetic-test-key"); - await scheduleJobs(); - expect(fetchTeams).toHaveBeenCalledTimes(1); - await vi.advanceTimersByTimeAsync(24 * 60 * 60 * 1000); - expect(fetchTeams).toHaveBeenCalledTimes(2); - expect(fetchMatches).toHaveBeenCalledTimes(24); - }); - - it("reports failed request cleanup without skipping draft cleanup or the next run", async () => { - vi.spyOn(console, "error").mockImplementation(() => undefined); - vi.mocked(deleteOldRequests).mockRejectedValueOnce( - new Error("private database details"), - ); - await scheduleJobs(); - await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000); - expect(expireReportsInProgress).toHaveBeenCalledOnce(); - expect(console.error).toHaveBeenCalledWith( - "Old request cleanup failed", - expect.objectContaining({ name: "Error" }), - ); - expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain( - "private database details", - ); - await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000); - expect(deleteOldRequests).toHaveBeenCalledTimes(2); - expect(expireReportsInProgress).toHaveBeenCalledTimes(2); - }); - - it.each(["teams", "matches"] as const)( - "reports a failed %s refresh and runs again on schedule", - async (job) => { - vi.stubEnv("TBA_KEY", "synthetic-test-key"); - vi.spyOn(console, "error").mockImplementation(() => undefined); - await scheduleJobs(); - const task = { - teams: fetchTeams, - matches: fetchMatches, - }[job]; - vi.mocked(task).mockRejectedValueOnce( - new Error("private provider details"), - ); - const period = (job === "matches" ? 1 : 24) * 60 * 60 * 1000; - const initialCalls = vi.mocked(task).mock.calls.length; - await vi.advanceTimersByTimeAsync(period); - expect(console.error).toHaveBeenCalledWith( - job === "matches" - ? "TBA match refresh failed" - : "TBA daily refresh failed", - expect.objectContaining({ name: "Error" }), - ); - expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain( - "private provider details", - ); - await vi.advanceTimersByTimeAsync(period); - expect(vi.mocked(task).mock.calls.length).toBe(initialCalls + 2); - }, - ); - - it("preserves production imports when a key is absent", async () => { - vi.stubEnv("NODE_ENV", "production"); - vi.mocked(fetchTeams).mockRejectedValueOnce(new Error("TBA unauthorized")); - await expect(scheduleJobs()).rejects.toThrow("TBA unauthorized"); - }); +test("API scheduler starts without provider credentials or periodic work", async () => { + const interval = vi.spyOn(globalThis, "setInterval"); + try { + await expect(scheduleJobs()).resolves.toBeUndefined(); + expect(interval).not.toHaveBeenCalled(); + } finally { + interval.mockRestore(); + } }); - -it.each([true, false])( - "skips the team import when the dev team table has data (%s)", - async (hasTeams) => { - vi.useFakeTimers(); - vi.stubEnv("NODE_ENV", "development"); - vi.stubEnv("TBA_KEY", "synthetic-test-key"); - vi.mocked(prisma.team.count).mockResolvedValue(hasTeams ? 1 : 0); - vi.clearAllMocks(); - try { - await scheduleJobs(); - expect(fetchTeams).toHaveBeenCalledTimes(hasTeams ? 0 : 1); - } finally { - vi.clearAllTimers(); - vi.useRealTimers(); - vi.unstubAllEnvs(); - } - }, -); diff --git a/apps/worker/README.md b/apps/worker/README.md index 57d4596d5..faa060c7e 100644 --- a/apps/worker/README.md +++ b/apps/worker/README.md @@ -171,10 +171,10 @@ Match refresh intervals use event-local dates and hours: | ------------------------------ | ------------- | -------------- | | Event dates, 07:00–21:00 local | 1 minute | 1 hour | | Event dates, overnight | 15 minutes | 1 hour | -| Starts within 7 days | 30 minutes | 6 hours | +| Starts within 7 days | 6 hours | 6 hours | | Starts later, or dates unknown | 1 day | 1 day | | Ended within 7 days | 6 hours | 1 day | -| Older event | 7 days | 7 days | +| Older event | Explicit only | Explicit only | Missing or invalid timezones fall back to UTC. Activity is inferred from dates, not from a live event status feed. Due match jobs near the event's date window @@ -238,8 +238,7 @@ import { refreshTournamentGaps } from "./src/jobs/gaps"; await refreshTournamentGaps("2026casj"); ``` -Or queue `bun run enqueue gaps 2026casj` for the worker. Explicit gap jobs repeat -daily; normal match jobs already recalculate gaps on every refresh. Apply the +Or queue `bun run enqueue gaps 2026casj` for the worker. Explicit gap jobs run once; normal match jobs already recalculate gaps on every refresh. Apply the shared database migration and rebuild the database package before running the updated worker. @@ -298,3 +297,36 @@ data. A fresh empty response clears withdrawn data, while HTTP 304 preserves it. ### Historical seasons Run `bun run backfill 1992 2025` with the target database and TBA credentials configured to queue archived season imports. With no arguments, it queues every season from 1992 through the current year. Existing jobs keep their leases and retry schedules. Tournament and district imports queue event and district details through the existing scheduler, so the backfill continues on the worker. + + +## Finite batches (LVT-382) + +`bun run batch` (`WORKER_MODE=batch bun index.ts`) reconciles once, snapshots +eligible due job IDs, runs each at most once with `WORKER_CONCURRENCY` consumers, +then disconnects Prisma and exits. It opens no health listener and has no polling +between executions. The process owns its client; do not share a batch client with +another service. The default `WORKER_MODE=continuous` retains the existing active +event loop and `/health` readiness checks. + +Snapshot jobs are claimed atomically with fresh leases at execution time. Other +replicas, changed schedules, and active leases can make an ID ineligible; it is +left for the next window. Retry delays and TBA Retry-After remain durable. A +failed job does not stop other jobs. Claim/planner/database errors fail the batch +after other consumers drain. Shutdown stops new claims and waits for running +imports and lease heartbeats before disconnecting. + +Jobs discovered by a catalog import wait until the next batch. For a new/empty +database, run another batch after catalogs complete to import child events and +districts before accepting traffic. Never promise active-event freshness with a +daily batch. Archived events (more than seven event-local days after completion), +old season catalogs and explicit gap jobs finalize after one successful run; +failures remain queued. Existing archived recurring jobs get one final execution. +Normal planning does not recreate archived events. Use `backfill` for historical +years or explicitly enqueue individual archived event jobs when needed. + +Daily `maintenance global` work now removes expired verification requests, +unverified registrations older than a day, abandons expired report drafts and +scrubs their payloads at day thirty. API startup creates no import or cleanup +timers and needs no TBA key. Read-time report and verification expiry checks stay +in the API. Import ownership overlaps LVT-335; resource/pool tuning remains with +LVT-376. See [batch rollout](../../docs/worker-batch-rollout.md) before cutover. diff --git a/apps/worker/index.ts b/apps/worker/index.ts index da0a3a52a..395d010e2 100644 --- a/apps/worker/index.ts +++ b/apps/worker/index.ts @@ -1,6 +1,6 @@ import { db } from "./src/db"; import { tba } from "./src/tba"; -import { runWorker } from "./src/worker"; +import { runBatch, runWorker } from "./src/worker"; import { createHealthApp, healthPort } from "./src/server"; // Validate the provider configuration before starting any background work. @@ -10,6 +10,10 @@ const shutdown = new AbortController(); const stop = () => shutdown.abort(); let lastReconciledAt = 0; +const mode = process.env.WORKER_MODE ?? "continuous"; +if (!["batch", "continuous"].includes(mode)) + throw new Error("WORKER_MODE must be batch or continuous"); + const port = healthPort(); const concurrency = Number(process.env.WORKER_CONCURRENCY ?? 2); const app = createHealthApp({ @@ -22,24 +26,25 @@ const app = createHealthApp({ }, }); -// Migrations are owned by the release/API service, never each worker replica. -await db.$queryRaw`SELECT 1 FROM "ImportJob", "FetchState", "TournamentGap" LIMIT 0`; - -const server = Bun.serve({ hostname: "0.0.0.0", port, fetch: app.fetch }); -console.info( - `Worker started with ${concurrency} consumers; health port ${port}`, -); - process.once("SIGINT", stop); process.once("SIGTERM", stop); +let server: ReturnType | undefined; try { - await runWorker(db, shutdown.signal, concurrency, () => { - lastReconciledAt = Date.now(); - }); + // Batch has no listener or readiness queries between windows. + if (mode === "batch") { + await runBatch(db, shutdown.signal, concurrency); + } else { + // Migrations are owned by the release/API service. + await db.$queryRaw`SELECT 1 FROM "ImportJob", "FetchState", "TournamentGap" LIMIT 0`; + server = Bun.serve({ hostname: "0.0.0.0", port, fetch: app.fetch }); + await runWorker(db, shutdown.signal, concurrency, () => { + lastReconciledAt = Date.now(); + }); + } } finally { process.removeListener("SIGINT", stop); process.removeListener("SIGTERM", stop); - await server.stop(true); + await server?.stop(true); await db.$disconnect(); } diff --git a/apps/worker/package.json b/apps/worker/package.json index 788c91df2..7fb70a736 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -5,6 +5,7 @@ "private": true, "scripts": { "start": "bun run index.ts", + "batch": "WORKER_MODE=batch bun run index.ts", "enqueue": "bun run src/enqueue.ts", "backfill": "bun run src/backfill.ts", "postinstall": "npm --prefix ../../packages/db ci --include=dev && npm --prefix ../../packages/db run build", diff --git a/apps/worker/src/jobs/maintenance.ts b/apps/worker/src/jobs/maintenance.ts new file mode 100644 index 000000000..c91a9ed75 --- /dev/null +++ b/apps/worker/src/jobs/maintenance.ts @@ -0,0 +1,28 @@ +import type { PrismaClient } from "@lovat/db"; + +export async function runMaintenance(db: PrismaClient, now = new Date()) { + await db.emailVerificationRequest.deleteMany({ + where: { expiresAt: { lt: now } }, + }); + await db.registeredTeam.deleteMany({ + where: { + timeCreated: { lt: new Date(now.getTime() - 86_400_000) }, + emailVerified: false, + }, + }); + await db.scoutReportInProgress.updateMany({ + where: { + status: { in: ["LOADED", "STARTED", "ENDED"] }, + expiresAt: { lte: now }, + }, + data: { status: "ABANDONED" }, + }); + await db.scoutReportInProgress.updateMany({ + where: { + status: "ABANDONED", + expiresAt: { lte: new Date(now.getTime() - 23 * 86_400_000) }, + NOT: { payload: { equals: {} } }, + }, + data: { payload: {} }, + }); +} diff --git a/apps/worker/src/schedule.ts b/apps/worker/src/schedule.ts index 9f7cc1752..797a658c1 100644 --- a/apps/worker/src/schedule.ts +++ b/apps/worker/src/schedule.ts @@ -57,7 +57,7 @@ export function tournamentCadence(event: EventDates, now = new Date()) { return { phase: "upcoming", - matches: soon ? 30 * minute : day, + matches: soon ? 6 * hour : day, roster: soon ? 6 * hour : day, } as const; } @@ -65,7 +65,7 @@ export function tournamentCadence(event: EventDates, now = new Date()) { const recent = today - event.endDate.getTime() <= 7 * day; return { - phase: "finished", + phase: recent ? "finished" : "archived", matches: recent ? 6 * hour : 7 * day, roster: recent ? day : 7 * day, } as const; diff --git a/apps/worker/src/scheduler.ts b/apps/worker/src/scheduler.ts index edbcd0e12..2afe9e52c 100644 --- a/apps/worker/src/scheduler.ts +++ b/apps/worker/src/scheduler.ts @@ -12,6 +12,7 @@ import { TbaHttpError } from "./providers/tba"; import { day, hour, minute, tournamentCadence } from "./schedule"; export const jobKinds = [ + "maintenance", "teams", "tournaments", "team-seasons", @@ -38,7 +39,7 @@ export async function enqueueImport( if (["tournaments", "team-seasons", "districts"].includes(kind)) validateSeason(Number(targetKey)); - if (kind === "teams" && targetKey !== "global") + if (["teams", "maintenance"].includes(kind) && targetKey !== "global") throw new Error("Team catalog target must be global"); // Preserve existing leases, retry delays and recurring run times. @@ -89,6 +90,7 @@ export async function reconcileSchedule( db: PrismaClient, now = new Date(), year = now.getUTCFullYear(), + includeArchived = false, ) { validateSeason(year); @@ -117,16 +119,20 @@ export async function reconcileSchedule( existing.get(`${kind}:${target}`), ); - await ensure("teams", "global", 7 * day); - await ensure("tournaments", String(year), 6 * hour); - await ensure("team-seasons", String(year), 7 * day); - await ensure("districts", String(year), day); + if (year === now.getUTCFullYear()) { + await ensure("maintenance", "global", day); + await ensure("teams", "global", 7 * day); + await ensure("tournaments", String(year), 6 * hour); + await ensure("team-seasons", String(year), 7 * day); + await ensure("districts", String(year), day); + } for (const district of districts) await ensure("district-teams", district.key, day); for (const tournament of tournaments) { const cadence = tournamentCadence(tournament, now); + if (cadence.phase === "archived" && !includeArchived) continue; await ensure("tournament-teams", tournament.key, cadence.roster); await ensure("tournament-details", tournament.key, cadence.roster); @@ -134,7 +140,12 @@ export async function reconcileSchedule( } } -export async function claimJob(db: PrismaClient, now = new Date()) { +export async function claimJob( + db: PrismaClient, + now = new Date(), + id: string | null = null, + cutoff = now, +) { const token = crypto.randomUUID(); const expires = new Date(now.getTime() + leaseMs); @@ -144,7 +155,8 @@ export async function claimJob(db: PrismaClient, now = new Date()) { SET "leaseToken" = ${token}, "leaseExpiresAt" = ${expires} FROM ( SELECT "id" FROM "ImportJob" - WHERE "runAt" <= ${now} + WHERE "runAt" <= ${cutoff} + AND (${id}::text IS NULL OR "id" = ${id}) AND ("leaseExpiresAt" IS NULL OR "leaseExpiresAt" <= ${now}) ORDER BY CASE WHEN "kind" = 'matches' AND EXISTS ( @@ -170,6 +182,11 @@ export async function executeImport( job: Pick, db: PrismaClient, ) { + if (job.kind === "maintenance") { + const { runMaintenance } = await import("./jobs/maintenance"); + return runMaintenance(db); + } + const { tba } = await import("./tba"); const dependencies = { db, tba }; const year = Number(job.targetKey); @@ -179,12 +196,22 @@ export async function executeImport( return importAllTeams(dependencies); case "tournaments": await importTournaments(year, year, dependencies); - return reconcileSchedule(db, new Date(), year); + return reconcileSchedule( + db, + new Date(), + year, + year < new Date().getUTCFullYear(), + ); case "team-seasons": return importTeamSeasons(year, dependencies); case "districts": await importDistricts(year, dependencies); - return reconcileSchedule(db, new Date(), year); + return reconcileSchedule( + db, + new Date(), + year, + year < new Date().getUTCFullYear(), + ); case "district-teams": return importDistrictTeams(job.targetKey, dependencies); case "tournament-teams": @@ -201,7 +228,18 @@ export async function executeImport( } async function refreshInterval(db: PrismaClient, job: ImportJob, now: Date) { - if (job.kind === "gaps") return day; + if (job.kind === "maintenance") return day; + if (job.kind === "gaps") return null; + if ( + ["tournaments", "team-seasons", "districts"].includes(job.kind) && + Number(job.targetKey) < now.getUTCFullYear() + ) + return null; + if ( + job.kind === "district-teams" && + Number(job.targetKey.slice(0, 4)) < now.getUTCFullYear() + ) + return null; if (job.kind === "teams" || job.kind === "team-seasons") return 7 * day; if (job.kind === "tournaments") return 6 * hour; if (job.kind === "districts" || job.kind === "district-teams") return day; @@ -211,6 +249,8 @@ async function refreshInterval(db: PrismaClient, job: ImportJob, now: Date) { }); const cadence = tournamentCadence(event, now); + if (cadence.phase === "archived") return null; + return job.kind === "matches" ? cadence.matches : cadence.roster; } @@ -230,15 +270,35 @@ export function retryDelay(attempts: number, error: unknown, now = new Date()) { export async function runNextJob( db: PrismaClient, execute: (job: ImportJob, db: PrismaClient) => Promise = executeImport, + claim: { cutoff: Date; id: string } | undefined = undefined, ) { - const job = await claimJob(db); + const job = await claimJob(db, new Date(), claim?.id, claim?.cutoff); if (!job) return false; + const startedAt = Date.now(); + const log = (event: string, extra: Record = {}) => + console.info( + JSON.stringify({ + event, + kind: job.kind, + target: job.targetKey, + attempt: job.attempts + 1, + durationMs: Date.now() - startedAt, + queueDelayMs: Math.max(0, startedAt - job.runAt.getTime()), + ...extra, + }), + ); + log("job.started"); + let renewal: Promise | undefined; let renewing = false; let lostLease = false; - const heartbeat = setInterval(async () => { + const heartbeat = setInterval(() => { + if (!renewing && !lostLease) renewal = renew(); + }, 30_000); + + const renew = async () => { if (renewing || lostLease) return; renewing = true; @@ -260,7 +320,7 @@ export async function runNextJob( } finally { renewing = false; } - }, 30_000); + }; try { await execute(job, db); @@ -269,6 +329,18 @@ export async function runNextJob( const interval = await refreshInterval(db, job, now); if (!lostLease) { + const where = { + id: job.id, + leaseToken: job.leaseToken, + leaseExpiresAt: { gt: now }, + }; + if (interval === null) { + const completed = await db.importJob.deleteMany({ where }); + log(completed.count === 1 ? "job.completed" : "job.lease_lost", { + finalized: true, + }); + return true; + } const completed = await db.importJob.updateMany({ where: { id: job.id, @@ -284,9 +356,9 @@ export async function runNextJob( }, }); if (completed.count === 1) { - console.info( - `Import completed: ${job.kind} ${job.targetKey}; next refresh ${new Date(now.getTime() + interval).toISOString()}`, - ); + log("job.completed", { + nextRunAt: new Date(now.getTime() + interval).toISOString(), + }); } } } catch (error) { @@ -316,9 +388,13 @@ export async function runNextJob( }); } - console.error(`Import failed: ${job.kind} ${job.targetKey} (${lastError})`); + log("job.failed", { + error: lastError, + retryDelayMs: retryDelay(job.attempts, error, now), + }); } finally { clearInterval(heartbeat); + await renewal; } return true; diff --git a/apps/worker/src/worker.ts b/apps/worker/src/worker.ts index 52bc9b34a..7fedc4d56 100644 --- a/apps/worker/src/worker.ts +++ b/apps/worker/src/worker.ts @@ -60,3 +60,67 @@ export async function runWorker( ...Array.from({ length: concurrency }, consumer), ]); } + +/** A fixed snapshot prevents short recurrences, retries and child jobs from looping. */ +export async function runBatch( + db: PrismaClient, + signal: AbortSignal, + concurrency = 2, + dependencies = { reconcileSchedule, runNextJob }, +) { + const startedAt = Date.now(); + try { + if ( + !Number.isSafeInteger(concurrency) || + concurrency < 1 || + concurrency > 16 + ) { + throw new Error("Worker concurrency must be an integer between 1 and 16"); + } + if (signal.aborted) return; + await dependencies.reconcileSchedule(db); + const cutoff = new Date(); + const jobs = await db.importJob.findMany({ + where: { + runAt: { lte: cutoff }, + OR: [{ leaseExpiresAt: null }, { leaseExpiresAt: { lte: cutoff } }], + }, + select: { id: true }, + orderBy: [{ runAt: "asc" }, { id: "asc" }], + }); + let cursor = 0; + let processed = 0; + // Wait for every consumer before disconnecting, including on claim errors. + const results = await Promise.allSettled( + Array.from({ length: concurrency }, async () => { + while (!signal.aborted) { + const job = jobs[cursor++]; + if (!job) return; + if ( + await dependencies.runNextJob(db, undefined, { cutoff, id: job.id }) + ) + processed++; + } + }), + ); + const failed = results.find((result) => result.status === "rejected"); + if (failed?.status === "rejected") throw failed.reason; + console.info( + JSON.stringify({ + event: "batch.completed", + eligible: jobs.length, + processed, + interrupted: signal.aborted, + durationMs: Date.now() - startedAt, + }), + ); + } finally { + await db.$disconnect(); + console.info( + JSON.stringify({ + event: "batch.disconnected", + at: new Date().toISOString(), + }), + ); + } +} diff --git a/apps/worker/test/batch.test.ts b/apps/worker/test/batch.test.ts new file mode 100644 index 000000000..b7d4fa057 --- /dev/null +++ b/apps/worker/test/batch.test.ts @@ -0,0 +1,85 @@ +import { expect, test } from "bun:test"; +import type { PrismaClient } from "@lovat/db"; +import { runBatch } from "../src/worker"; + +function fixture(ids = ["a", "b", "c"]) { + let disconnected = false; + const db = { + importJob: { findMany: async () => ids.map((id) => ({ id })) }, + $disconnect: async () => { + disconnected = true; + }, + } as unknown as PrismaClient; + return { db, disconnected: () => disconnected }; +} + +test("batch processes each snapshot member once with bounded concurrency and disconnects", async () => { + const f = fixture(); + const seen: string[] = []; + let running = 0; + let peak = 0; + await runBatch(f.db, new AbortController().signal, 2, { + reconcileSchedule: async () => {}, + runNextJob: async (_db, _execute, claim) => { + seen.push(claim!.id); + peak = Math.max(peak, ++running); + await new Promise((resolve) => setTimeout(resolve, 2)); + expect(f.disconnected()).toBe(false); + running--; + return true; + }, + }); + expect(seen.sort()).toEqual(["a", "b", "c"]); + expect(peak).toBe(2); + expect(f.disconnected()).toBe(true); +}); + +test("batch waits for other consumers before disconnecting on claim failure", async () => { + const f = fixture(); + let drained = false; + await expect( + runBatch(f.db, new AbortController().signal, 2, { + reconcileSchedule: async () => {}, + runNextJob: async (_db, _execute, claim) => { + if (claim!.id === "a") throw new Error("claim failed"); + await new Promise((resolve) => setTimeout(resolve, 2)); + expect(f.disconnected()).toBe(false); + drained = true; + return true; + }, + }), + ).rejects.toThrow("claim failed"); + expect(drained).toBe(true); + expect(f.disconnected()).toBe(true); +}); + +test("abort drains current work without new claims", async () => { + const f = fixture(); + const controller = new AbortController(); + const seen: string[] = []; + await runBatch(f.db, controller.signal, 1, { + reconcileSchedule: async () => {}, + runNextJob: async (_db, _execute, claim) => { + seen.push(claim!.id); + controller.abort(); + return true; + }, + }); + expect(seen).toEqual(["a"]); + expect(f.disconnected()).toBe(true); +}); + +test("planner failure and invalid concurrency also disconnect", async () => { + for (const concurrency of [0, 2]) { + const f = fixture(); + await expect( + runBatch(f.db, new AbortController().signal, concurrency, { + reconcileSchedule: async () => { + throw new Error("planner failed"); + }, + runNextJob: async () => false, + }), + ).rejects.toThrow(); + expect(f.disconnected()).toBe(true); + } +}); diff --git a/apps/worker/test/maintenance.integration.test.ts b/apps/worker/test/maintenance.integration.test.ts new file mode 100644 index 000000000..abe29bf0e --- /dev/null +++ b/apps/worker/test/maintenance.integration.test.ts @@ -0,0 +1,112 @@ +import { expect, test } from "bun:test"; +import { runMaintenance } from "../src/jobs/maintenance"; +import { day } from "../src/schedule"; + +const enabled = process.env.LOVAT_DB_TEST === "1"; + +test.skipIf(!enabled)( + "maintenance preserves live and submitted drafts and scrubs old abandoned payloads", + async () => { + const url = new URL( + process.env.DATABASE_URL ?? "postgresql://localhost/missing", + ); + if ( + !["localhost", "127.0.0.1"].includes(url.hostname) || + url.pathname !== "/lovat_test" + ) { + throw new Error("Use only a disposable local lovat_test database"); + } + const { createDb } = await import("@lovat/db"); + const db = createDb(url.href); + const fixture = crypto.randomUUID(); + const number = 8_000_000 + Math.floor(Math.random() * 1_000_000); + const now = new Date(); + try { + await db.team.create({ data: { number, name: "Maintenance fixture" } }); + await db.registeredTeam.create({ + data: { + number, + code: fixture, + email: "fixture@example.invalid", + emailVerified: true, + timeCreated: new Date(0), + }, + }); + const scouter = await db.scouter.create({ + data: { sourceTeamNumber: number }, + }); + for (const [suffix, status, age] of [ + ["live", "LOADED", -day], + ["expired", "STARTED", 0], + ["old", "ENDED", 24 * day], + ["submitted", "SUBMITTED", 24 * day], + ] as const) { + await db.scoutReportInProgress.create({ + data: { + uuid: `${fixture}-${suffix}`, + sourceTeamNumber: number, + scouterUuid: scouter.uuid, + deviceId: fixture, + seasonYear: 2026, + schemaVersion: 1, + mode: "COMPETITION", + status, + tournamentKey: "2026fixture", + matchType: "QUALIFICATION", + matchNumber: 1, + teamNumber: number, + ...(status === "SUBMITTED" + ? { startedAt: now, endedAt: now, submittedAt: now } + : {}), + payload: { fixture: true }, + expiresAt: new Date(now.getTime() - age), + }, + }); + } + for (const [suffix, age] of [ + ["expired", day], + ["live", -day], + ] as const) { + await db.emailVerificationRequest.create({ + data: { + verificationCode: `${fixture}-${suffix}`, + email: "fixture@example.invalid", + teamNumber: number, + expiresAt: new Date(now.getTime() - age), + }, + }); + } + await runMaintenance(db, now); + await runMaintenance(db, now); + const rows = await db.scoutReportInProgress.findMany({ + where: { sourceTeamNumber: number }, + }); + expect(rows.find((r) => r.uuid.endsWith("-live"))?.status).toBe("LOADED"); + expect(rows.find((r) => r.uuid.endsWith("-expired"))?.status).toBe( + "ABANDONED", + ); + expect(rows.find((r) => r.uuid.endsWith("-expired"))?.payload).toEqual({ + fixture: true, + }); + expect(rows.find((r) => r.uuid.endsWith("-old"))?.payload).toEqual({}); + expect(rows.find((r) => r.uuid.endsWith("-submitted"))?.payload).toEqual({ + fixture: true, + }); + expect(rows.find((r) => r.uuid.endsWith("-submitted"))?.status).toBe( + "SUBMITTED", + ); + expect( + await db.emailVerificationRequest.count({ + where: { teamNumber: number }, + }), + ).toBe(1); + expect(await db.registeredTeam.count({ where: { number } })).toBe(1); + } finally { + await db.team.deleteMany({ where: { number } }); + await db.emailVerificationRequest.deleteMany({ + where: { teamNumber: number }, + }); + await db.$disconnect(); + } + }, +); diff --git a/apps/worker/test/schedule.test.ts b/apps/worker/test/schedule.test.ts index a9088fc8c..40fb03dd6 100644 --- a/apps/worker/test/schedule.test.ts +++ b/apps/worker/test/schedule.test.ts @@ -17,7 +17,7 @@ test("uses local event dates, including the last day after UTC midnight", () => }); expect(tournamentCadence(event, new Date("2026-03-05T03:00:00Z"))).toEqual({ phase: "upcoming", - matches: 30 * minute, + matches: 6 * hour, roster: 6 * hour, }); expect(tournamentCadence(event, new Date("2026-03-06T10:00:00Z"))).toEqual({ diff --git a/apps/worker/test/scheduler.integration.test.ts b/apps/worker/test/scheduler.integration.test.ts index b49a1449b..4cb6dccb7 100644 --- a/apps/worker/test/scheduler.integration.test.ts +++ b/apps/worker/test/scheduler.integration.test.ts @@ -240,3 +240,58 @@ test.skipIf(!enabled)( } }, ); + +test.skipIf(!enabled)( + "snapshot claims use a fresh lease and exclude rescheduled jobs", + async () => { + const cutoff = new Date(Date.now() - 10 * minute); + const job = await enqueueImport( + db, + "gaps", + `${fixture}-snapshot`, + new Date(0), + ); + try { + const claimed = await claimJob(db, new Date(), job.id, cutoff); + expect(claimed?.leaseExpiresAt!.getTime()).toBeGreaterThan( + Date.now() + minute, + ); + await db.importJob.update({ + where: { id: job.id }, + data: { leaseToken: null, leaseExpiresAt: null, runAt: new Date() }, + }); + expect(await claimJob(db, new Date(), job.id, cutoff)).toBeNull(); + } finally { + await db.importJob.delete({ where: { id: job.id } }); + } + }, +); + +test.skipIf(!enabled)( + "one-shot gaps finalize only with the owned lease; failures stay durable", + async () => { + const job = await enqueueImport( + db, + "gaps", + `${fixture}-finalize`, + new Date(0), + ); + await runNextJob( + db, + async () => { + throw new Error("retry"); + }, + { id: job.id, cutoff: new Date() }, + ); + expect( + (await db.importJob.findUniqueOrThrow({ where: { id: job.id } })) + .attempts, + ).toBe(1); + await db.importJob.update({ + where: { id: job.id }, + data: { runAt: new Date(0) }, + }); + await runNextJob(db, async () => {}, { id: job.id, cutoff: new Date() }); + expect(await db.importJob.findUnique({ where: { id: job.id } })).toBeNull(); + }, +); diff --git a/apps/worker/test/tournament-schedule.test.ts b/apps/worker/test/tournament-schedule.test.ts index c15129a70..603adf64a 100644 --- a/apps/worker/test/tournament-schedule.test.ts +++ b/apps/worker/test/tournament-schedule.test.ts @@ -29,3 +29,35 @@ for (const timestamp of ["2026-12-31T23:59:59Z", "2027-01-01T00:00:00Z"]) { ]); }); } + +test("archived events are only discovered during explicit backfill", async () => { + const queued: string[] = []; + const db = { + districtSeason: { findMany: async () => [] }, + tournament: { + findMany: async () => [ + { + key: "2025test", + startDate: new Date("2025-03-01Z"), + endDate: new Date("2025-03-02Z"), + timezone: "UTC", + }, + ], + }, + importJob: { + findMany: async () => [], + upsert: async ({ create }: { create: { kind: string } }) => { + queued.push(create.kind); + return create; + }, + }, + } as unknown as PrismaClient; + await reconcileSchedule(db, new Date("2026-11-19Z"), 2025); + expect(queued).toEqual([]); + await reconcileSchedule(db, new Date("2026-11-19Z"), 2025, true); + expect(queued.sort()).toEqual([ + "matches", + "tournament-details", + "tournament-teams", + ]); +}); diff --git a/docs/worker-batch-rollout.md b/docs/worker-batch-rollout.md new file mode 100644 index 000000000..ef2b64cdd --- /dev/null +++ b/docs/worker-batch-rollout.md @@ -0,0 +1,118 @@ +# Worker batch rollout and sleep verification + +## Implemented behavior + +LVT-382 adds finite batch execution, durable maintenance, structured job logs and +an opt-in Railway Cron configuration. No schema migration is required. Merging +does not enable database sleeping or change the running worker to Cron. API-owned +TBA imports and periodic maintenance are removed; deploy the worker first and +verify its maintenance job before deploying the API. + +## Operating schedule + +Use the existing `.railway/railway.ts` named partial and authenticated CLI linked +to the intended environment. `RAILWAY_WORKER_CRON` is a **local IaC input** which +sets Worker `WORKER_MODE=batch`, Cron, and restart policy NEVER, and removes the +continuous health check. Supply the same input for every plan/apply; otherwise +the graph returns the worker to continuous mode and clears Cron. Confirm that the +plan clears the old health check/Cron/restart settings before applying. Never run +both a second polling worker and the Cron worker when trying to measure sleep. + +| Phase | IaC input / operation | Match cadence when running | +| --- | --- | --- | +| Offseason | `RAILWAY_WORKER_CRON='0 18 * * *'` | Daily due-work window | +| Within seven days before an event | `RAILWAY_WORKER_CRON='0 */6 * * *'` | Four batches/day | +| Competition dates | Unset Cron input; apply continuous graph before local 07:00 | One minute 07:00–21:00 local; 15 minutes overnight | +| First seven days after event | Four batches/day, then return to daily | Six hours | +| Archived | Explicit backfill/enqueue only | Finalize after success | + +18:00 UTC is provisional, not a measured optimal start time. Choose the actual +window using demand logs and deploy constraints. Global weekly team imports and +daily season/district/maintenance work share each batch; shorter queue intervals +never wake a stopped process. Failures wait until the next external window once +their retry delay has elapsed. If urgent, trigger a manual batch after that delay. + +Schedule both calendar cutovers before enabling Cron: enter continuous mode before +the earliest event's local morning, and restore four/daily windows after the last +event's local end. The application automatically slows job recurrence after an +event, but **does not change Railway's operating mode or Cron schedule**. Until an +operator or off-process orchestrator has scheduled and verified both transitions, +keep continuous mode. A five-minute Cron cannot provide minute-level freshness. +New catalog child jobs wait for the next snapshot; bootstrap with an additional +manual batch before switching API traffic or entering competition mode. + +Railway requires Cron processes to close connections and exit; running jobs can +cause later scheduled starts to be skipped. See the [Cron documentation](https://docs.railway.com/cron-jobs). + +## Remaining wake sources + +- API requests that use Prisma, including authentication and queue writes. +- API `/status` currently responds without querying the database. It is not a + readiness proof. Coordinate any probe changes with LVT-339. +- Continuous Worker `/health` queries `SELECT 1`; its planner and consumers poll + every 30/5 seconds. Batch mode exposes no listener. +- Active training WebSocket sessions poll the database; idle API startup also + ensures the built-in training exercise. Audit session lifetimes and restart + frequency before interpreting sleep results. +- Each process's shared PrismaPg pool currently allows ten connections with a + five-minute idle timeout. Batch disconnect closes its pool; API pools remain. + Pool tuning belongs to LVT-376. Do not infer sleeping from a lack of API events. +- Release migrations, manual SQL, dashboards, previews pointed at the same DB, + third-party uptime checks, public DB connections and database monitoring may + keep the database awake. Verify actual platform network and sleep behavior. + +## Preview verification and production gate + +1. Verify an isolated preview Postgres/Redis and sandbox provider keys. Apply the + existing schema via the API/release migration owner. Back up operational config. +2. Deploy worker code in continuous mode; verify maintenance and current-year + imports. Deploy the API; start it with unavailable TBA and confirm serving and + report lifecycle tests pass without API ingestion. During a rolling upgrade, + old API replicas can retain timers: drain them before measuring ownership. +3. Apply the Cron graph in the preview. Verify exit code zero, `batch.disconnected`, + no persistent worker connections, and no worker readiness probes between runs. + Trigger an overlapping batch to verify leases, interrupt a batch and verify + reclaim after 90 seconds, and simulate provider failure/429 with retry delay. +4. After auditing the wake sources, enable PostgreSQL Serverless in the preview. + Observe a whole quiet interval and its next batch/request. Record **actual** + platform sleep/resume transitions, connection counts and memory, plus p50/p95 + cold first-query/API latency, errors, and a warm-request comparison. Ensure + readiness behavior and connection timeouts still allow correct responses. +5. Compare equal baseline/post-change windows: awake hours, sleep hours, memory + GiB-hours, platform cost and traffic/event volume. Reconcile these against + provider billing. Production response gaps (including the reported 7.6-hour + maximum) do not measure Railway sleep and are not cost savings evidence. +6. Only after preview evidence and scheduled event cutovers, apply the reviewed + production graph, retain one worker, and monitor overdue work and API latency. + Do not enable database sleeping as an incidental consequence of merging code. + +## Observability and rollback + +JSON `job.started`, `job.completed`, `job.failed` include kind, target, attempt, +queue delay and duration. Completion includes next run or finalization; failure +includes sanitized error and retry delay. `batch.completed` includes eligible and +processed counts, interruption and duration. `batch.disconnected` records when +Prisma disconnect finished, not the server's measured last query or sleep time. +Use DB/platform metrics for actual activity, sleep, connection and cost evidence. +Alert on missing scheduled completion, repeated retries, overdue jobs and active +matches older than their event cadence. Logs contain no scouting payloads. + +Rollback scheduling by unsetting `RAILWAY_WORKER_CRON`, reviewing/applying the +continuous graph and verifying `/health` plus fresh matches. Disable database +sleep if cold-start correctness regresses. Keep the new API import ownership; +restoring old API timers alongside Worker duplicates ingestion. Queue explicit +historical jobs to restore needed archived refreshes. Durable jobs and leases +survive restarts; successful finalized imports remain in their data tables. + +## Evidence recorded for this change + +Local fixture-backed PostgreSQL tests cover leases, retries, atomic ingestion, +archival finalization and fresh leases against an older snapshot. Batch tests +cover bounded consumers, stopping claims on abort, draining before disconnect +and disconnect on planner/claim failure. Deployment graph tests cover Cron and +continuous configurations. + +As of 2026-11-19, the connected Railway account lists only `crux`, not Lovat. +No Lovat preview or production settings were changed. Actual sleep windows, +billing impact, cold-start measurements, demand-selected timing and production +cutover remain unverified; LVT-382 must remain open until those gates are met. From fa365e6c428d91514f403297ab932a641aa14b69 Mon Sep 17 00:00:00 2001 From: jackshim415 Date: Thu, 19 Nov 2026 08:11:07 -0800 Subject: [PATCH 2/2] Clarify Railway CLI access and pending operational verification --- docs/worker-batch-rollout.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/worker-batch-rollout.md b/docs/worker-batch-rollout.md index ef2b64cdd..280a893df 100644 --- a/docs/worker-batch-rollout.md +++ b/docs/worker-batch-rollout.md @@ -112,7 +112,9 @@ cover bounded consumers, stopping claims on abort, draining before disconnect and disconnect on planner/claim failure. Deployment graph tests cover Cron and continuous configurations. -As of 2026-11-19, the connected Railway account lists only `crux`, not Lovat. -No Lovat preview or production settings were changed. Actual sleep windows, -billing impact, cold-start measurements, demand-selected timing and production -cutover remain unverified; LVT-382 must remain open until those gates are met. +As of 2026-11-19, the Railway plugin connection lists only `crux`; the local +CLI independently has Lovat access and PR #132 provisions a preview automatically. +No sleep or Cron settings were applied by this change. Actual sleep windows, +billing impact, cold-start measurements, demand-selected timing and scheduled +production cutovers remain unverified; LVT-382 must remain open until those +operational gates are met.