Skip to content

Add import-job lifecycle: cancel in-progress and delete finished jobs - #8975

Merged
Git-on-my-level merged 1 commit into
BasedHardware:mainfrom
ZachL111:zach/import-job-lifecycle
Jul 5, 2026
Merged

Git-on-my-level merged 1 commit into
BasedHardware:mainfrom
ZachL111:zach/import-job-lifecycle

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

What

Users can start (POST /v1/import/limitless), list (GET /v1/import/jobs), and check the status of an import job, but there was no way to cancel a stuck or running import or remove a finished/failed one, so old jobs pile up in the list with no recourse. This adds the two missing lifecycle verbs. It sits in the actively-built ChatGPT/Claude/Limitless memory-bank import area (#4862, #8764), and it wires up the delete_import_job db helper that already shipped but was never called by any router.

Purely additive: no existing route or behavior changes.

Changes

  • models/import_job.py — add a cancelled status to ImportJobStatus.
  • routers/imports.py
    • POST /v1/import/jobs/{job_id}/cancel — cancels a pending or processing job (sets cancelled + an error note); 409 if the job is already terminal.
    • DELETE /v1/import/jobs/{job_id} — deletes a terminal job (completed/failed/cancelled); 409 while it is still in progress (cancel first).
    • Both mirror the existing get_import_job_status ownership checks (404 unknown, 403 wrong owner). The two endpoints form a clean state machine (cancel for in-progress, delete for terminal), so the delete path never races the background worker.
  • utils/imports/limitless.py — the worker re-reads the job right before its final status write and bails if it was cancelled, so a mid-run cancel is not overwritten by completed/failed.

Tests

tests/routers/test_imports.py (14 cases): cancel of pending/processing sets cancelled and calls update_import_job; cancel of a terminal job is 409; delete of completed/failed/cancelled calls delete_import_job; delete of an in-progress job is 409; and both 404 on a missing job and 403 on a wrong-owner job. The module is imported normally and the db helpers are patched (no sys.modules mutation, no network).

Review in cubic

@cubic-dev-ai cubic-dev-ai 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.

1 issue found across 4 files

Confidence score: 2/5

  • In backend/routers/imports.py (cancel endpoint via update_import_job), there’s a race where a cancel request can overwrite a job that already finished because the Firestore write is unconditional; merging as-is could leave users with incorrect final job states and potentially trigger wrong downstream behavior. Add a transaction or compare-and-set precondition on the status update (and reject stale cancels) before merging.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/routers/imports.py">

<violation number="1" location="backend/routers/imports.py:183">
P1: The cancel endpoint can overwrite a job that finished between the status check and the update. Because `update_import_job` does a raw Firestore write with no transaction or CAS precondition, a background worker that transitions the job to `completed`/`failed` after the `if` check but before the update will have its result silently lost. The user sees `cancelled` even though the import actually succeeded, which breaks the intended state machine and can lead to unnecessary re-imports. Consider wrapping the check-and-update in a Firestore transaction so the cancellation only applies when the status is still `pending` or `processing` at the moment of the write.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

if job.get('status') not in (ImportJobStatus.pending.value, ImportJobStatus.processing.value):
raise HTTPException(status_code=409, detail="Only a pending or processing import can be cancelled")

import_jobs_db.update_import_job(job_id, {'status': ImportJobStatus.cancelled.value, 'error': 'Cancelled by user'})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: The cancel endpoint can overwrite a job that finished between the status check and the update. Because update_import_job does a raw Firestore write with no transaction or CAS precondition, a background worker that transitions the job to completed/failed after the if check but before the update will have its result silently lost. The user sees cancelled even though the import actually succeeded, which breaks the intended state machine and can lead to unnecessary re-imports. Consider wrapping the check-and-update in a Firestore transaction so the cancellation only applies when the status is still pending or processing at the moment of the write.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/imports.py, line 183:

<comment>The cancel endpoint can overwrite a job that finished between the status check and the update. Because `update_import_job` does a raw Firestore write with no transaction or CAS precondition, a background worker that transitions the job to `completed`/`failed` after the `if` check but before the update will have its result silently lost. The user sees `cancelled` even though the import actually succeeded, which breaks the intended state machine and can lead to unnecessary re-imports. Consider wrapping the check-and-update in a Firestore transaction so the cancellation only applies when the status is still `pending` or `processing` at the moment of the write.</comment>

<file context>
@@ -169,6 +169,44 @@ def get_import_job_status(
+    if job.get('status') not in (ImportJobStatus.pending.value, ImportJobStatus.processing.value):
+        raise HTTPException(status_code=409, detail="Only a pending or processing import can be cancelled")
+
+    import_jobs_db.update_import_job(job_id, {'status': ImportJobStatus.cancelled.value, 'error': 'Cancelled by user'})
+    return ImportJobResponse(
+        job_id=job['id'],
</file context>

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @ZachL111 — this is a well-structured, purely-additive change that fills a real gap in the import-job lifecycle, and the test coverage is thorough (14 cases, all green). A few notes for a maintainer:

  1. CI: the Backend unit suite failure is unrelated to this PR — the 3 failures are in test_backend_runtime_env_validator.py (Cloud Run/gateway/OAuth-secret validation) and reproduce on the main track; all 14 of this PR's own tests in test_imports.py pass.

  2. Race on cancel (agreeing with @cubic-dev-ai): cancel_import_job does a read-then-write on Firestore with no transaction/CAS precondition, so in a narrow window a background worker could flip the job to completed/failed between the status check and the update, and the cancel would then overwrite that true terminal status. Low severity in practice (conversations are persisted before the final status write, so no data is lost — the user just sees cancelled instead of completed), but wrapping the check-and-update in a Firestore transaction with a status precondition would make the state machine airtight. The worker-side guard (skip the final write if the job is already cancelled) correctly handles the reverse race.

  3. Minor: the os.environ.setdefault("ENCRYPTION_SECRET", ...) in tests/routers/test_imports.py is redundant — backend/tests/conftest.py already sets the same hermetic fixture value. Safe to drop.

Leaving this for human maintainer review since it touches user-data persistence.

@Git-on-my-level Git-on-my-level added the needs-maintainer-review Needs a human maintainer to sign off before merge label Jul 4, 2026
Users could start, list, and check import jobs but never cancel a stuck or running import or
remove a finished one, so failed jobs accumulated with no recourse. This wires up the two missing
verbs (the delete_import_job db helper already existed but was never called by a router).

- models/import_job.py: add a cancelled status.
- routers/imports.py: POST /v1/import/jobs/{job_id}/cancel (pending/processing -> cancelled, 409
  otherwise) and DELETE /v1/import/jobs/{job_id} (terminal states only, 409 while in progress).
  Both mirror the existing 404/403 ownership checks.
- utils/imports/limitless.py: the worker re-reads the job before its final status write and skips
  it if the job was cancelled, so a mid-run cancel is not overwritten by completed/failed.
@ZachL111
ZachL111 force-pushed the zach/import-job-lifecycle branch from f6ba752 to 7ff8a2c Compare July 4, 2026 11:06

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed: scoped backend addition, approve-only per policy (features/new endpoints are Nik's merge call).

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for this, @ZachL111 — clean implementation. A few observations from automated review:

Strengths

  • The cancel/delete split forms a tidy state machine (cancel for pending/processing, delete for terminal), so the delete path never races the worker.
  • Both endpoints correctly mirror the existing ownership pattern (404 unknown, 403 wrong owner) from get_import_job_status.
  • The worker re-read-and-bail guard in limitless.py is a nice touch — it ensures a mid-run cancel sticks instead of being overwritten by the final completed/failed write.
  • Good test coverage (14 cases across both endpoints, including 404/403/409 paths). All CI green.

Minor notes for a human maintainer

  • The cancel is cooperative (sets a status flag the worker checks before its final write) rather than a hard interrupt, so in-flight file processing continues until the worker naturally finishes. That is a reasonable trade-off for a background import, but worth a conscious call.
  • The os.environ.setdefault("ENCRYPTION_SECRET", ...) in the new test file is redundant — tests/conftest.py already sets the same value. Harmless (setdefault is a no-op once conftest runs), but could be dropped.
  • The DELETE endpoint permanently removes the job record from Firestore; if there is any audit/retention expectation on import-job metadata, that is a product call for a maintainer.

This touches user-data persistence and auth surfaces, so formal approval is intentionally withheld — human maintainer review is needed before merge. The implementation itself looks solid.

Automated review by Omi PR maintainer monitor (glm-5.2). AI-agent review — please factor that into your judgment.

@Git-on-my-level
Git-on-my-level merged commit 93a4043 into BasedHardware:main Jul 5, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants