Skip to content

Add queue timeout for stuck pre-running submissions#5144

Draft
RishabhJain2018 wants to merge 1 commit into
masterfrom
cursor/submission-queue-timeout-e826
Draft

Add queue timeout for stuck pre-running submissions#5144
RishabhJain2018 wants to merge 1 commit into
masterfrom
cursor/submission-queue-timeout-e826

Conversation

@RishabhJain2018

@RishabhJain2018 RishabhJain2018 commented Jul 9, 2026

Copy link
Copy Markdown
Member

Summary

Adds automatic cleanup for submissions stuck in pre-running queue states (submitted, submitting, queued, resuming) — the class of issues seen with FALCON H1 submissions after the June 30 outage.

Changes

  • New challenge field: submission_queue_time_limit (default 7200s / 2 hours). Set to 0 to disable per challenge.
  • Core logic: apps/jobs/queue_timeout.py finds timed-out submissions and marks them failed with stderr "Submission exceeded the queue time limit and was not picked up for evaluation."
  • Management command: python manage.py fail_stuck_submissions [--challenge-pk PK] [--dry-run]
  • Celery beat task: jobs.tasks.fail_stuck_submissions_task runs every 30 minutes
  • Staff API: submission_queue_time_limit added to update_challenge_attributes allowed fields

How it works

  1. A periodic job scans submissions in pre-running states where COALESCE(rerun_resumed_at, submitted_at) exceeds the challenge's submission_queue_time_limit.
  2. Matching submissions are marked failed, completed_at is set, and stderr is written.
  3. trigger_eks_node_autoscale is called for docker-based challenges.

Configuration

Method Example
Django Admin Edit submission_queue_time_limit on the Challenge
Staff API POST /api/challenges/challenge/update_challenge_attributes/ with submission_queue_time_limit
challenge_config.yaml submission_queue_time_limit: 3600
Disable Set submission_queue_time_limit: 0

Notes

  • This is separate from submission_time_limit (execution timeout once a pod is running).
  • Existing stuck submissions will be cleaned up on the next beat run after deploy + migration.
  • Manual one-off: python manage.py fail_stuck_submissions --dry-run then without --dry-run.

Testing

Added tests/unit/jobs/test_queue_timeout.py. Could not run pytest in this cloud VM (no Docker/Python deps); please verify in CI or local dev environment.

Slack Thread

Open in Web Open in Cursor 

Summary by CodeRabbit

  • New Features

    • Added a configurable submission queue timeout for challenges.
    • Submissions that stay queued too long can now be automatically marked failed.
    • Added a scheduled background check to run this cleanup regularly.
    • Added a command to manually run the check, with optional dry-run and challenge-specific filtering.
  • Bug Fixes

    • Queue timeout timing now respects resumed submissions correctly.
    • Updated challenge editing and creation flows to include the new timeout setting.

Introduce submission_queue_time_limit on Challenge (default 2 hours) and
periodic cleanup via fail_stuck_submissions management command and Celery
beat task. Submissions in submitted/submitting/queued/resuming states that
exceed the limit are marked failed with a clear stderr message.

Co-authored-by: Rishabh Jain <rishabhjain2018@gmail.com>
@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Adds a configurable per-challenge submission_queue_time_limit, exposed via serializers and the challenge update endpoint. Introduces apps/jobs/queue_timeout.py logic to detect and fail submissions stuck in pre-running states, wired via a new management command and a 30-minute Celery beat task, with accompanying unit tests.

Changes

Auto-fail submissions stuck in queue

Layer / File(s) Summary
Challenge queue time limit field and exposure
apps/challenges/models.py, apps/challenges/serializers.py, apps/challenges/views.py
submission_queue_time_limit becomes a PositiveIntegerField (default 7200) with explanatory help text, exposed in ChallengeSerializer and ZipChallengeSerializer, and added to the editable field allowlist in update_challenge_attributes.
Queue timeout detection and failure logic
apps/jobs/queue_timeout.py
New module adds get_stuck_submission_queryset, is_submission_queue_timed_out, fail_submission_due_to_queue_timeout, and fail_stuck_submissions, which identify queue-stuck submissions past their per-challenge limit, mark them FAILED with completed_at/stderr.txt, trigger EKS autoscale, and log results.
Management command and Celery beat scheduling
apps/jobs/management/commands/fail_stuck_submissions.py, apps/jobs/tasks.py, settings/common.py
Adds a fail_stuck_submissions command with --challenge-pk and --dry-run options, a fail_stuck_submissions_task Celery task, and a 30-minute CELERY_BEAT_SCHEDULE entry to run it periodically.
Unit tests for queue timeout logic
tests/unit/jobs/test_queue_timeout.py
New test module covers timeout evaluation, fail/skip/dry-run/challenge-filter behaviors, queryset status filtering, and task delegation.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Command as fail_stuck_submissions_task/Command
  participant Job as fail_stuck_submissions
  participant Query as get_stuck_submission_queryset
  participant DB as Submission
  participant EKS as trigger_eks_node_autoscale

  Command->>Job: fail_stuck_submissions(challenge_pk, dry_run)
  Job->>Query: get_stuck_submission_queryset(challenge_pk)
  Query->>DB: filter queue-stuck submissions
  DB-->>Job: submission list
  loop each submission
    Job->>Job: is_submission_queue_timed_out(submission)
    alt timed out
      Job->>DB: fail_submission_due_to_queue_timeout(submission)
      DB->>DB: status=FAILED, completed_at, stderr.txt
      DB->>EKS: trigger_eks_node_autoscale(current/previous status)
    end
  end
  Job-->>Command: failed count
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding queue timeout handling for stuck pre-running submissions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cursor/submission-queue-timeout-e826

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.


try:
os.makedirs("/tmp/evalai")
except OSError:

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
apps/jobs/queue_timeout.py (1)

62-66: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant submission.save() after stderr_file.save().

FileField.save() with the default save=True already calls instance.save() internally, persisting status, completed_at, and the new stderr_file path. The explicit submission.save() on line 66 is an unnecessary extra database write.

♻️ Proposed refactor
     submission.stderr_file.save(
         "stderr.txt",
         ContentFile(QUEUE_TIMEOUT_STDERR.encode("utf-8")),
     )
-    submission.save()

     challenge = submission.challenge_phase.challenge
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/jobs/queue_timeout.py` around lines 62 - 66, The queue timeout handling
in submission processing has a redundant extra save after writing the stderr
file. In the code that uses submission.stderr_file.save, remove the explicit
submission.save() because FileField.save() already persists the model by
default; keep the stderr_file save as the single persistence step and ensure the
submission status/completed_at updates remain in the same flow around that call.
tests/unit/jobs/test_queue_timeout.py (1)

214-225: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add test coverage for SUBMITTING and RESUMING queue states.

The queryset test only validates SUBMITTED, QUEUED, and RUNNING. Per the PR objectives, STUCK_QUEUE_STATUSES also includes submitting and resuming. Adding assertions for these two statuses would verify the full inclusion set and guard against accidental filter regressions.

As per path instructions, tests should cover edge cases and not silently pass.

♻️ Proposed addition
 def test_get_stuck_submission_queryset_includes_queue_states(self):
     submitted = self._create_submission(status=Submission.SUBMITTED)
     queued = self._create_submission(status=Submission.QUEUED)
+    submitting = self._create_submission(status=Submission.SUBMITTING)
+    resuming = self._create_submission(status=Submission.RESUMING)
     running = self._create_submission(status=Submission.RUNNING)

     stuck_pks = set(
         get_stuck_submission_queryset().values_list("pk", flat=True)
     )

     self.assertIn(submitted.pk, stuck_pks)
     self.assertIn(queued.pk, stuck_pks)
+    self.assertIn(submitting.pk, stuck_pks)
+    self.assertIn(resuming.pk, stuck_pks)
     self.assertNotIn(running.pk, stuck_pks)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/jobs/test_queue_timeout.py` around lines 214 - 225, The queryset
test for get_stuck_submission_queryset currently covers only SUBMITTED, QUEUED,
and RUNNING, so extend test_get_stuck_submission_queryset_includes_queue_states
to also create submissions in SUBMITTING and RESUMING and assert both pks are
included in stuck_pks. Use the existing _create_submission helper and Submission
status constants to keep the test aligned with STUCK_QUEUE_STATUSES and guard
against regressions in the queue-state filter.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/jobs/queue_timeout.py`:
- Around line 88-108: The batch loop in queue_timeout should isolate failures
per submission so one bad item does not stop processing the rest. Wrap the body
of the per-submission logic around get_stuck_submission_queryset() and
fail_submission_due_to_queue_timeout() in a try/except, log the exception with
submission.pk and challenge.pk for context, and then continue to the next
submission. Keep the existing warning path for successful timeouts, and make
sure the error handling preserves the loop behavior in queue_timeout.py.

---

Nitpick comments:
In `@apps/jobs/queue_timeout.py`:
- Around line 62-66: The queue timeout handling in submission processing has a
redundant extra save after writing the stderr file. In the code that uses
submission.stderr_file.save, remove the explicit submission.save() because
FileField.save() already persists the model by default; keep the stderr_file
save as the single persistence step and ensure the submission
status/completed_at updates remain in the same flow around that call.

In `@tests/unit/jobs/test_queue_timeout.py`:
- Around line 214-225: The queryset test for get_stuck_submission_queryset
currently covers only SUBMITTED, QUEUED, and RUNNING, so extend
test_get_stuck_submission_queryset_includes_queue_states to also create
submissions in SUBMITTING and RESUMING and assert both pks are included in
stuck_pks. Use the existing _create_submission helper and Submission status
constants to keep the test aligned with STUCK_QUEUE_STATUSES and guard against
regressions in the queue-state filter.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 5131df87-f8dc-4415-a28f-48fa04a85ba5

📥 Commits

Reviewing files that changed from the base of the PR and between 337b404 and c46e3e0.

⛔ Files ignored due to path filters (1)
  • apps/challenges/migrations/0128_challenge_submission_queue_time_limit.py is excluded by !**/migrations/**
📒 Files selected for processing (8)
  • apps/challenges/models.py
  • apps/challenges/serializers.py
  • apps/challenges/views.py
  • apps/jobs/management/commands/fail_stuck_submissions.py
  • apps/jobs/queue_timeout.py
  • apps/jobs/tasks.py
  • settings/common.py
  • tests/unit/jobs/test_queue_timeout.py

Comment on lines +88 to +108
for submission in get_stuck_submission_queryset(challenge_pk):
if not is_submission_queue_timed_out(submission, now=now):
continue

previous_status = submission.status
queue_started_at = submission.rerun_resumed_at or submission.submitted_at
challenge = submission.challenge_phase.challenge

if fail_submission_due_to_queue_timeout(submission, dry_run=dry_run):
failed_count += 1
action = "Would fail" if dry_run else "Failed"
logger.warning(
"%s queue-stuck submission pk=%s challenge_pk=%s status=%s "
"queue_started_at=%s queue_time_limit=%ss",
action,
submission.pk,
challenge.pk,
previous_status,
queue_started_at,
challenge.submission_queue_time_limit,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Missing per-submission error handling in batch loop.

If fail_submission_due_to_queue_timeout raises an exception for any single submission (e.g., storage failure on stderr_file.save(), or trigger_eks_node_autoscale AWS API error), the exception propagates and terminates the loop. All remaining stuck submissions are skipped until the next 30-minute cycle.

The autoscale failure case is particularly concerning: the submission is already persisted as FAILED by stderr_file.save(), so the next run won't pick it up (it's no longer in STUCK_QUEUE_STATUSES), but the autoscale trigger is permanently lost.

Wrap each iteration in a try/except, log the error, and continue processing the rest.

🛡️ Proposed fix
     for submission in get_stuck_submission_queryset(challenge_pk):
         if not is_submission_queue_timed_out(submission, now=now):
             continue

         previous_status = submission.status
         queue_started_at = submission.rerun_resumed_at or submission.submitted_at
         challenge = submission.challenge_phase.challenge

-        if fail_submission_due_to_queue_timeout(submission, dry_run=dry_run):
-            failed_count += 1
-            action = "Would fail" if dry_run else "Failed"
-            logger.warning(
-                "%s queue-stuck submission pk=%s challenge_pk=%s status=%s "
-                "queue_started_at=%s queue_time_limit=%ss",
-                action,
-                submission.pk,
-                challenge.pk,
-                previous_status,
-                queue_started_at,
-                challenge.submission_queue_time_limit,
-            )
+        try:
+            if fail_submission_due_to_queue_timeout(
+                submission, dry_run=dry_run
+            ):
+                failed_count += 1
+                action = "Would fail" if dry_run else "Failed"
+                logger.warning(
+                    "%s queue-stuck submission pk=%s challenge_pk=%s "
+                    "status=%s queue_started_at=%s "
+                    "queue_time_limit=%ss",
+                    action,
+                    submission.pk,
+                    challenge.pk,
+                    previous_status,
+                    queue_started_at,
+                    challenge.submission_queue_time_limit,
+                )
+        except Exception:
+            logger.exception(
+                "Failed to process queue-stuck submission pk=%s "
+                "challenge_pk=%s status=%s",
+                submission.pk,
+                challenge.pk,
+                previous_status,
+            )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for submission in get_stuck_submission_queryset(challenge_pk):
if not is_submission_queue_timed_out(submission, now=now):
continue
previous_status = submission.status
queue_started_at = submission.rerun_resumed_at or submission.submitted_at
challenge = submission.challenge_phase.challenge
if fail_submission_due_to_queue_timeout(submission, dry_run=dry_run):
failed_count += 1
action = "Would fail" if dry_run else "Failed"
logger.warning(
"%s queue-stuck submission pk=%s challenge_pk=%s status=%s "
"queue_started_at=%s queue_time_limit=%ss",
action,
submission.pk,
challenge.pk,
previous_status,
queue_started_at,
challenge.submission_queue_time_limit,
)
for submission in get_stuck_submission_queryset(challenge_pk):
if not is_submission_queue_timed_out(submission, now=now):
continue
previous_status = submission.status
queue_started_at = submission.rerun_resumed_at or submission.submitted_at
challenge = submission.challenge_phase.challenge
try:
if fail_submission_due_to_queue_timeout(
submission, dry_run=dry_run
):
failed_count += 1
action = "Would fail" if dry_run else "Failed"
logger.warning(
"%s queue-stuck submission pk=%s challenge_pk=%s "
"status=%s queue_started_at=%s "
"queue_time_limit=%ss",
action,
submission.pk,
challenge.pk,
previous_status,
queue_started_at,
challenge.submission_queue_time_limit,
)
except Exception:
logger.exception(
"Failed to process queue-stuck submission pk=%s "
"challenge_pk=%s status=%s",
submission.pk,
challenge.pk,
previous_status,
)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/jobs/queue_timeout.py` around lines 88 - 108, The batch loop in
queue_timeout should isolate failures per submission so one bad item does not
stop processing the rest. Wrap the body of the per-submission logic around
get_stuck_submission_queryset() and fail_submission_due_to_queue_timeout() in a
try/except, log the exception with submission.pk and challenge.pk for context,
and then continue to the next submission. Keep the existing warning path for
successful timeouts, and make sure the error handling preserves the loop
behavior in queue_timeout.py.

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.

2 participants