Skip to content

feat: scheduled sweeper to eventually resolve stuck jobs - #147

Merged
TytaniumDev merged 9 commits into
mainfrom
feat/stale-job-sweeper
Apr 10, 2026
Merged

TytaniumDev merged 9 commits into
mainfrom
feat/stale-job-sweeper

Conversation

@TytaniumDev

Copy link
Copy Markdown
Owner

Summary

  • Adds api/lib/stale-sweeper.ts with a pure shouldHardCancelSim predicate plus side-effecting helpers (hardCancelStaleSimsForJob, hardFailStaleQueuedJob, sweepStaleJobs).
  • Adds POST /api/admin/sweep-stale-jobs (authed with the existing WORKER_SECRET header) as the Cloud Scheduler target.
  • Adds 10 unit tests for the predicate + 4 SQLite integration tests that cover the full sweep flow (empty list, young job no-op, old-RUNNING cancel+aggregate, old-QUEUED hard-fail). Integration tests gracefully skip when better-sqlite3 bindings cannot load locally; they always run in CI.
  • Adds docs/STALE_SWEEPER.md with the one-time Cloud Scheduler setup command and the tunable env vars.
  • Includes the design spec (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 uxBSYQvYB4JNoycuLSzz sat stuck at 24/25 sims for ~12 hours. A worker restart orphaned sim_003 in RUNNING, and when stale-detection finally marked it PENDING and 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

  • No manual intervention required. Every 15 min Cloud Scheduler fires the sweep.
  • Hard cap: no sim can block a job longer than 2h past job.startedAt — after that it's force-cancelled and the existing aggregation path runs on the remaining sims.
  • Race-safe: conditional Firestore/SQLite writes ensure a worker completing a sim always wins over a sweeper cancel.
  • Isolated failures: one broken job's error never stops the sweep.
  • Free-tier friendly: 1 Cloud Scheduler job (of 3 free/mo), minimal Firestore reads.

Test plan

  • npm run lint --prefix api passes
  • npm run lint --prefix frontend passes
  • npm run build --prefix frontend passes
  • npm run build --prefix api passes (new route shows up in the build output)
  • npx tsx api/lib/stale-sweeper.test.ts — 10/10 unit tests pass locally
  • CI runs full test:unit chain including the 4 SQLite integration tests
  • After merge: run the one-time gcloud scheduler jobs create http stale-sweeper ... command from docs/STALE_SWEEPER.md
  • Manually invoke the endpoint once with curl -X POST -H "X-Worker-Secret: ..." to verify the SweepResult shape

🤖 Generated with Claude Code

TytaniumDev and others added 7 commits April 10, 2026 01:51
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]>
@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, 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

  • Stale Job Sweeper Implementation: Introduced a new module api/lib/stale-sweeper.ts that provides logic to identify and resolve stuck jobs by hard-cancelling simulations exceeding a 2-hour lifetime cap and hard-failing stale queued jobs.
  • New Admin Endpoint: Added POST /api/admin/sweep-stale-jobs to trigger the sweeper, secured with the existing WORKER_SECRET header for use with Cloud Scheduler.
  • Testing and Documentation: Added comprehensive unit and SQLite integration tests for the sweeper logic, and included operational documentation in docs/STALE_SWEEPER.md for setup and configuration.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All CI checks passed.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

TytaniumDev and others added 2 commits April 10, 2026 10:44
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]>

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread api/lib/stale-sweeper.ts
*/
import * as Sentry from '@sentry/nextjs';
import type { Job, SimulationStatus } from './types';
import * as jobStore from './job-store-factory';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Add the isTerminalSimState import to allow using the shared state machine logic instead of hardcoding terminal states throughout this module.

Suggested change
import * as jobStore from './job-store-factory';
import * as jobStore from './job-store-factory';
import { isTerminalSimState } from '@shared/types/state-machine';
References
  1. 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.

Comment thread api/lib/stale-sweeper.ts
nowMs: number,
thresholdMs: number = SIM_HARD_CANCEL_THRESHOLD_MS
): boolean {
if (sim.state === 'COMPLETED' || sim.state === 'CANCELLED') return false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Use the isTerminalSimState helper for consistency with the rest of the application's state machine logic.

Suggested change
if (sim.state === 'COMPLETED' || sim.state === 'CANCELLED') return false;
if (isTerminalSimState(sim.state)) return false;
References
  1. 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.

Comment thread api/lib/stale-sweeper.ts
Comment on lines +178 to +188
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;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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
  1. 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.

Comment thread api/lib/stale-sweeper.ts
Comment on lines +181 to +183
const allTerminal =
sims.length > 0 &&
sims.every((s) => s.state === 'COMPLETED' || s.state === 'CANCELLED');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Use the isTerminalSimState helper here to ensure that the logic for identifying terminal simulations remains consistent with the core job store implementation.

Suggested change
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
  1. 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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
  1. 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.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, sweepStaleJobs
  • api/app/api/admin/sweep-stale-jobs/route.ts — HTTP endpoint wiring
  • api/lib/stale-sweeper.test.ts — 10 unit tests + 4 SQLite integration tests
  • api/package.json — test:unit chain update
  • DATA_FLOW.md and docs/STALE_SWEEPER.md — Documentation

Verified

  • All factory methods called by the sweeper (listActiveJobs, setJobFailed, conditionalUpdateSimulationStatus, recoverStaleJob, getJob, getSimulationStatuses, aggregateJobResults) exist in api/lib/job-store-factory.ts.
  • Auth pattern (bypass in local mode, isWorkerRequest in GCP mode) matches the existing /api/admin/pull-image endpoint exactly.
  • completedAt: new Date(nowMs).toISOString() is the correct type for SimulationStatus.completedAt (string, not Date).
  • The comment "recoverStaleJob's built-in re-trigger is gated on GCP mode" is accurate: recoverStaleSimulations returns early with false in local mode (if (!USE_FIRESTORE) return false), so step 4 is the only aggregation trigger for the local/SQLite path.
  • Conditional writes in hardCancelStaleSimsForJob correctly use ['PENDING', 'RUNNING', 'FAILED'] so a worker winning a sim at the last millisecond is never overwritten.
  • aggregateJobResults has an idempotency guard (job.status === 'COMPLETED' → early return), protecting against any concurrent invocations.

@TytaniumDev
TytaniumDev merged commit 1b56dc5 into main Apr 10, 2026
20 checks passed
@TytaniumDev
TytaniumDev deleted the feat/stale-job-sweeper branch April 10, 2026 17:50
TytaniumDev added a commit that referenced this pull request Apr 10, 2026
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]>
TytaniumDev added a commit that referenced this pull request Apr 10, 2026
…#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant