Repository navigation
feat: scheduled sweeper to eventually resolve stuck jobs - #147
Conversation
Design for a scheduled sweeper that guarantees jobs eventually reach a terminal state even if a worker dies mid-sim or Pub/Sub starvation prevents a re-published message from being delivered. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
TDD plan for the scheduled stale-sweeper: - pure predicate + unit tests - side-effecting helpers (hardCancel, hardFail) - sweepStaleJobs orchestrator - SQLite integration tests - HTTP endpoint - package.json wiring and ops docs Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Adds api/lib/stale-sweeper.ts with the pure predicate shouldHardCancelSim plus side-effecting helpers hardCancelStaleSimsForJob, hardFailStaleQueuedJob, and the sweepStaleJobs orchestrator. Designed to be called on a 15-minute schedule; uses conditional writes so a worker completing a sim at the last moment always wins races against the sweeper. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
10 unit tests for shouldHardCancelSim covering every state transition and the boundary case, plus 4 integration tests exercising sweepStaleJobs against the real SQLite job store (scanned=0 on empty, young-job no-op, old-RUNNING cancel+aggregate, old-QUEUED hard-fail). Integration tests gracefully skip when better-sqlite3 bindings are not loadable so the suite still runs on environments without a matching compiled binding; CI's npm ci always produces a fresh binding. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Cloud Scheduler hits this endpoint every 15 minutes and the handler runs one sweepStaleJobs pass. Auth mirrors /api/admin/pull-image: X-Worker-Secret in production, bypassed in local mode. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a scheduled stale-job sweeper designed to automatically resolve stuck jobs in the system. By implementing a 2-hour lifetime cap for simulations and queued jobs, the sweeper ensures that jobs eventually reach a terminal state without requiring manual intervention. The solution is designed to be race-safe and isolated, ensuring that individual job failures do not impact the overall sweep process. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. Footnotes
|
There was a problem hiding this comment.
Code Review - Changes Requested
CLAUDE.md Violation: DATA_FLOW.md not updated
** requires** that be updated whenever changes alter the data flow, specifically listing "aggregation pipeline" as a covered area.
This PR introduces a new external aggregation trigger in api/lib/stale-sweeper.ts (lines 526–535):
// sweepStaleJobs — step 4
if (refreshed && refreshed.status === 'RUNNING') {
const sims = await jobStore.getSimulationStatuses(job.id);
const allTerminal = sims.length > 0 && sims.every(...);
if (allTerminal) {
await jobStore.aggregateJobResults(job.id); // new aggregation trigger
result.aggregationsTriggered += 1;
}
}Previously, aggregateJobResults was only called by the worker after sims completed. This PR adds a second path where Cloud Scheduler → POST /api/admin/sweep-stale-jobs → sweepStaleJobs drives aggregation for jobs whose sims were force-cancelled. DATA_FLOW.md must be updated to document this new trigger path in the aggregation pipeline section.
Required action: Update DATA_FLOW.md to describe the stale-sweeper as a second aggregation trigger and note that it runs on a 15-minute Cloud Scheduler cadence rather than inline with worker progress reporting.
Adds an "Other aggregation triggers" entry describing the new sweep-stale-jobs path: how it fits into the 15-minute Cloud Scheduler cadence, what steps it runs, and why step (d) (explicit aggregateJobResults call) is necessary for LOCAL mode where recoverStaleJob's built-in re-trigger is a no-op. Per CLAUDE.md, DATA_FLOW.md must be updated when changes alter the aggregation pipeline. The stale-sweeper introduces a second path that can drive aggregateJobResults outside of worker progress reporting. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements a 'Stale Job Sweeper' feature designed to prevent simulation jobs from remaining in non-terminal states indefinitely. It adds a new administrative endpoint, core logic for hard-cancelling stale simulations and failing stale queued jobs, along with associated tests and documentation. The review feedback suggests utilizing shared state machine helpers for terminal state checks to improve consistency, optimizing the sweep logic to avoid redundant database calls and potential duplicate aggregations in Firestore mode, and ensuring environment variables are configured correctly in tests before module imports.
| */ | ||
| import * as Sentry from '@sentry/nextjs'; | ||
| import type { Job, SimulationStatus } from './types'; | ||
| import * as jobStore from './job-store-factory'; |
There was a problem hiding this comment.
Add the isTerminalSimState import to allow using the shared state machine logic instead of hardcoding terminal states throughout this module.
| import * as jobStore from './job-store-factory'; | |
| import * as jobStore from './job-store-factory'; | |
| import { isTerminalSimState } from '@shared/types/state-machine'; |
References
- Address valid code quality suggestions immediately within the current pull request, even if it expands the scope. Do not defer them to a follow-up task.
| nowMs: number, | ||
| thresholdMs: number = SIM_HARD_CANCEL_THRESHOLD_MS | ||
| ): boolean { | ||
| if (sim.state === 'COMPLETED' || sim.state === 'CANCELLED') return false; |
There was a problem hiding this comment.
Use the isTerminalSimState helper for consistency with the rest of the application's state machine logic.
| if (sim.state === 'COMPLETED' || sim.state === 'CANCELLED') return false; | |
| if (isTerminalSimState(sim.state)) return false; |
References
- Address valid code quality suggestions immediately within the current pull request, even if it expands the scope. Do not defer them to a follow-up task.
| const refreshed = await jobStore.getJob(job.id); | ||
| if (refreshed && refreshed.status === 'RUNNING') { | ||
| const sims = await jobStore.getSimulationStatuses(job.id); | ||
| const allTerminal = | ||
| sims.length > 0 && | ||
| sims.every((s) => s.state === 'COMPLETED' || s.state === 'CANCELLED'); | ||
| if (allTerminal) { | ||
| await jobStore.aggregateJobResults(job.id); | ||
| result.aggregationsTriggered += 1; | ||
| } | ||
| } |
There was a problem hiding this comment.
This section performs redundant database operations and may cause duplicate aggregation attempts in Firestore mode. Wrap this block in if (!jobStore.isGcpMode()) to limit it to local mode as intended, and refactor to reuse simulation statuses fetched earlier in the loop.
References
- Address valid code quality suggestions immediately within the current pull request, even if it expands the scope. Do not defer them to a follow-up task.
| const allTerminal = | ||
| sims.length > 0 && | ||
| sims.every((s) => s.state === 'COMPLETED' || s.state === 'CANCELLED'); |
There was a problem hiding this comment.
Use the isTerminalSimState helper here to ensure that the logic for identifying terminal simulations remains consistent with the core job store implementation.
| const allTerminal = | |
| sims.length > 0 && | |
| sims.every((s) => s.state === 'COMPLETED' || s.state === 'CANCELLED'); | |
| const allTerminal = | |
| sims.length > 0 && | |
| sims.every((s) => isTerminalSimState(s.state)); |
References
- Address valid code quality suggestions immediately within the current pull request, even if it expands the scope. Do not defer them to a follow-up task.
| const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'stale-sweeper-test-')); | ||
| process.env.LOGS_DATA_DIR = tempDir; | ||
| // Ensure we are in LOCAL mode for this test run. | ||
| delete process.env.GOOGLE_CLOUD_PROJECT; |
There was a problem hiding this comment.
Configure the environment before any application code is imported. Manipulating process.env.GOOGLE_CLOUD_PROJECT at this point is ineffective because stale-sweeper and job-store-factory have already cached the environment variables during import.
References
- Address valid code quality suggestions immediately within the current pull request, even if it expands the scope. Do not defer them to a follow-up task.
There was a problem hiding this comment.
Code Review - Approved
No issues found. Checked for bugs, security issues, and CLAUDE.md compliance.
What was reviewed
api/lib/stale-sweeper.ts— Core sweeper logic:shouldHardCancelSim,hardCancelStaleSimsForJob,hardFailStaleQueuedJob,sweepStaleJobsapi/app/api/admin/sweep-stale-jobs/route.ts— HTTP endpoint wiringapi/lib/stale-sweeper.test.ts— 10 unit tests + 4 SQLite integration testsapi/package.json—test:unitchain updateDATA_FLOW.mdanddocs/STALE_SWEEPER.md— Documentation
Verified
- All factory methods called by the sweeper (
listActiveJobs,setJobFailed,conditionalUpdateSimulationStatus,recoverStaleJob,getJob,getSimulationStatuses,aggregateJobResults) exist inapi/lib/job-store-factory.ts. - Auth pattern (bypass in local mode,
isWorkerRequestin GCP mode) matches the existing/api/admin/pull-imageendpoint exactly. completedAt: new Date(nowMs).toISOString()is the correct type forSimulationStatus.completedAt(string, not Date).- The comment "recoverStaleJob's built-in re-trigger is gated on GCP mode" is accurate:
recoverStaleSimulationsreturns early withfalsein local mode (if (!USE_FIRESTORE) return false), so step 4 is the only aggregation trigger for the local/SQLite path. - Conditional writes in
hardCancelStaleSimsForJobcorrectly use['PENDING', 'RUNNING', 'FAILED']so a worker winning a sim at the last millisecond is never overwritten. aggregateJobResultshas an idempotency guard (job.status === 'COMPLETED'→ early return), protecting against any concurrent invocations.
The GET handler called recoverStaleJob() on every request for a RUNNING or QUEUED job. For a job with N simulations, that one GET fanned out to roughly N+2 Firestore reads — the job doc, the active workers collection, and every sim doc in the subcollection — because recoverStaleSimulations walks the full simulation list on each call. With the frontend polling an active job every couple of seconds, one person watching one 20-sim job burned through ~40k Firestore reads/ hour. That single user session could consume the entire 50k/day free tier, and it was almost certainly the reason /api/jobs/:id appeared 25 times in the OOM logs: each GET loaded the whole sim array into memory, sometimes concurrently. Recovery is already handled out-of-band by the scheduled stale-sweeper (scheduled sweeper PR #147, docs/STALE_SWEEPER.md): Cloud Scheduler hits /api/admin/sweep-stale-jobs every 15 minutes and that endpoint runs the same recoverStaleJob path for every active job. The GET path was a best-effort duplicate that cost hundreds of Firestore reads per poll. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…#151) The GET handler called recoverStaleJob() on every request for a RUNNING or QUEUED job. For a job with N simulations, that one GET fanned out to roughly N+2 Firestore reads — the job doc, the active workers collection, and every sim doc in the subcollection — because recoverStaleSimulations walks the full simulation list on each call. With the frontend polling an active job every couple of seconds, one person watching one 20-sim job burned through ~40k Firestore reads/ hour. That single user session could consume the entire 50k/day free tier, and it was almost certainly the reason /api/jobs/:id appeared 25 times in the OOM logs: each GET loaded the whole sim array into memory, sometimes concurrently. Recovery is already handled out-of-band by the scheduled stale-sweeper (scheduled sweeper PR #147, docs/STALE_SWEEPER.md): Cloud Scheduler hits /api/admin/sweep-stale-jobs every 15 minutes and that endpoint runs the same recoverStaleJob path for every active job. The GET path was a best-effort duplicate that cost hundreds of Firestore reads per poll. Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Summary
api/lib/stale-sweeper.tswith a pureshouldHardCancelSimpredicate plus side-effecting helpers (hardCancelStaleSimsForJob,hardFailStaleQueuedJob,sweepStaleJobs).POST /api/admin/sweep-stale-jobs(authed with the existingWORKER_SECRETheader) as the Cloud Scheduler target.better-sqlite3bindings cannot load locally; they always run in CI.docs/STALE_SWEEPER.mdwith the one-time Cloud Scheduler setup command and the tunable env vars.docs/superpowers/specs/2026-04-10-stuck-job-prevention-design.md) and the TDD plan (docs/superpowers/plans/2026-04-10-stuck-job-prevention.md) that drove the implementation.Why
Incident: job
uxBSYQvYB4JNoycuLSzzsat stuck at 24/25 sims for ~12 hours. A worker restart orphanedsim_003inRUNNING, and when stale-detection finally marked itPENDINGand re-published, the message was starved by a newer job's 24 backlogged Pub/Sub messages. Current recovery is GET-triggered, so if nobody opens the job page, nothing happens. The sweeper makes recovery periodic and adds a 2h absolute cap on any one sim so stuck jobs eventually aggregate with partial results.Guarantees
job.startedAt— after that it's force-cancelled and the existing aggregation path runs on the remaining sims.Test plan
npm run lint --prefix apipassesnpm run lint --prefix frontendpassesnpm run build --prefix frontendpassesnpm run build --prefix apipasses (new route shows up in the build output)npx tsx api/lib/stale-sweeper.test.ts— 10/10 unit tests pass locallytest:unitchain including the 4 SQLite integration testsgcloud scheduler jobs create http stale-sweeper ...command fromdocs/STALE_SWEEPER.mdcurl -X POST -H "X-Worker-Secret: ..."to verify the SweepResult shape🤖 Generated with Claude Code