Skip to content

feat(tasks): let task queues cancel their tasks when the warehouse is… - #2130

Merged
c-thiel merged 4 commits into
mainfrom
feat/task-entity-binding
Oct 17, 2026
Merged

c-thiel merged 4 commits into
mainfrom
feat/task-entity-binding

Conversation

@c-thiel

@c-thiel c-thiel commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Task queues can decide what deleting a warehouse does with their tasks. TaskConfig::on_warehouse_delete() returns OnWarehouseDelete::Block (default: the warehouse cannot be deleted while it has a task of this queue) or OnWarehouseDelete::Cancel (deleting the warehouse cancels the queue's tasks in that warehouse, running ones included; if the delete fails, the tasks stay). A warehouse with namespaces cannot be deleted, so the cancelled tasks belong to deleted tables, views and generic tables, or to the warehouse itself. The setting applies in every process that registers the queue; where the queue is not registered, its tasks block the delete.

All built-in queues keep Block. Without custom task queues, only the fixes below apply.

Also:

  • If a task is created in a warehouse while an instance admin deletes it, the delete fails with 409 WarehouseHasUnfinishedTasks (was 409 WarehouseNotEmpty). Retry the request. Other deletes lock the warehouse first, so the task is created only after the delete and then fails.
  • If a warehouse is protected or deleted by another request while an instance admin deletes it, the delete fails with a retryable 409, and nothing is cancelled. It used to report success although the warehouse was not deleted.
  • A worker stops after one attempt to record its outcome when the task no longer exists or the attempt already has an outcome, for example after the task was cancelled or timed out. It used to retry 5 times and log an error.
  • When a task is run again with "run now" while its previous attempt is still finishing, the late outcome of the previous attempt no longer removes the new run.

Related issue

None.

How was this tested?

  • Unit tests added or updated
  • Integration tests added or updated
  • Query engine: not applicable
  • Storage: not applicable
  • Authorization: not applicable

The classification of record errors was tested against PostgreSQL 17 for an API cancel, a timed-out task that was picked again, a warehouse deleted during a run, an outcome recorded twice (every order), a real deadlock, a serialization failure, a terminated connection and a pool timeout. Only the closed-attempt cases stop; all others retry.

Checklist

  • CI passes (tests, clippy, formatting)
  • SQL queries changed: updated .sqlx/ folder committed
  • Database schema changed: new migration added, no released migration edited
  • New or changed endpoint: authorization check added and OpenAPI spec updated
  • Permissions changed: OpenFGA model updated
  • Audit log fields changed: change note added in audit-format/unreleased/
  • Docs updated
  • CLA signed

Breaking changes

None.

Downstream follow-up

  • Added: lakekeeper::service::tasks::OnWarehouseDelete (Block, Cancel; #[non_exhaustive]), TaskConfig::on_warehouse_delete() with default Block in both open-api variants, is_task_attempt_closed, and the error-type constants TASK_ATTEMPT_ALREADY_COMPLETED_ERROR_TYPE and TASK_ATTEMPT_ALREADY_FAILED_ERROR_TYPE. Nothing renamed or removed; QueueRegistration and the CatalogStore traits are unchanged. Plus compiles unchanged.
  • Behaviour:
    • record_success, record_failure, record_success_in_transaction and the deserialization-failure path stop after one attempt, with an info log, when the task is gone (404) or the attempt already has an outcome (409 TaskAttemptAlreadyCompleted or TaskAttemptAlreadyFailed). Other errors, such as 409 TransactionFailed, still retry.
    • Code that calls CatalogTaskOps::record_task_* directly can use is_task_attempt_closed to decide whether to retry.
    • Recording an outcome for a task in scheduled state returns 404 or 409 and writes nothing.
  • A Cancel queue must be registered wherever the management API runs (zero workers is fine). Otherwise its tasks still block the delete there.

Release notes

Custom task queues can let warehouse deletion cancel their tasks (TaskConfig::on_warehouse_delete). Built-in queues are unchanged.

Bug Fixes

  • Deleting a warehouse while it is being protected. An instance admin's delete that ran at the same time as setting warehouse protection could report success and remove the warehouse's permissions, while the warehouse itself was kept. The delete now fails with a retryable conflict, and nothing is changed.
  • Running a task again while it finishes. "Run now" on a task whose previous attempt was still finishing could lose the new run. The new run is kept.

Summary by CodeRabbit

  • New Features
    • Warehouse deletion can cancel queued and running tasks in queues configured for cancellation, including legacy queue names.
    • Queues block deletion by default when tasks remain. If deletion fails, canceled tasks are restored.
  • Bug Fixes
    • Deletion reports a conflict if the warehouse changes while deletion is in progress, and detects unfinished tasks committed during deletion.
    • Closed task attempts no longer trigger retries or overwrite outcomes when a task is missing, already completed, or already failed.
    • Tasks rescheduled after a failed attempt remain queued when that earlier attempt later reports success.

… deleted

A warehouse cannot be deleted while any task row exists for it, so a queue whose tasks reschedule themselves makes its warehouse undeletable. Queues now choose with `TaskConfig::on_warehouse_delete()`: `Block`, the default and today's behaviour, or `Cancel`, which cancels the queue's tasks in that warehouse, running ones included, inside the delete transaction. Built-in queues keep `Block`, so pending purges still block deletion.

The cancel uses the existing `cancel_scheduled_tasks` and runs before `ensure_warehouse_spec_mutable` locks the warehouse row. A worker that records its outcome holds its task row and needs the warehouse row for the task_log foreign key, so cancelling under that lock would deadlock. No `CatalogStore` method is added and no lock is taken.

Warehouse delete reports races as retryable 409s:
- A task created after the unfinished-task check makes the DELETE fail on `task_warehouse_id_fk`. This is now reported as `WarehouseHasUnfinishedTasks`, not `WarehouseNotEmpty`.
- When the DELETE removes no row because the warehouse changed concurrently (protected or deleted by another request, possible for bypass callers), the delete returns a `ConcurrentModification` conflict. It used to report success, so authz cleanup and the deletion event ran for a warehouse that still existed.

Recording a task's outcome stops after one attempt when the task is gone (404), for example because its warehouse was deleted. A 409 still retries.
@coderabbitai

coderabbitai Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 35baf02a-831c-46e2-b25c-4852c4740f3d
📥 Commits

Reviewing files that changed from the base of the PR and between 20b3999 and 7932216.

📒 Files selected for processing: 3
  • crates/lakekeeper-integration-tests/tests/drop_warehouse.rs
  • crates/lakekeeper/src/service/tasks/mod.rs
  • crates/lakekeeper/src/service/tasks/task_registry.rs

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

Walkthrough

Warehouse task queues now define whether warehouse deletion blocks or cancels their tasks. Deletion applies configured cancellation within its transaction and handles concurrent changes. Task recording recognizes closed attempts and preserves scheduled tasks when an older attempt records an outcome. Tests cover these behaviors and related deletion conditions.

Changes

Warehouse task handling and deletion

Layer / File(s) Summary
Queue deletion policy and registration
crates/lakekeeper/src/service/tasks/mod.rs, crates/lakekeeper/src/service/tasks/task_registry.rs
Task queues now have a warehouse-deletion policy that defaults to Block. The registry records each policy and lists cancellation queues with their legacy names.
Deletion cancellation and storage handling
crates/lakekeeper/src/api/management/v1/warehouse/mod.rs, crates/lakekeeper-storage-postgres/src/warehouse.rs, crates/lakekeeper-integration-tests/tests/drop_warehouse.rs
Warehouse deletion cancels tasks from configured queues before checking spec mutability. Storage maps task foreign-key violations to WarehouseHasUnfinishedTasks and reports concurrent deletion changes. Integration tests cover cancellation, blocking, task scope, and deletion conditions.
Task attempt and scheduled-row handling
crates/lakekeeper/src/service/tasks/mod.rs, crates/lakekeeper-storage-postgres/src/tasks.rs
Task recording stops for closed attempts. Storage keeps scheduled task rows active when an older attempt records success or failure. Tests cover terminal errors and scheduled-row preservation.
Storage deletion behavior tests
crates/lakekeeper-storage-postgres/src/warehouse.rs
Tests cover task and protection changes during deletion, lock waits, and rejection when a namespace remains.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant WarehouseManagement
  participant RegisteredTaskQueues
  participant CatalogTaskOps
  participant PostgresWarehouseStorage
  WarehouseManagement->>RegisteredTaskQueues: get queues configured to cancel
  WarehouseManagement->>CatalogTaskOps: cancel warehouse tasks in the transaction
  WarehouseManagement->>PostgresWarehouseStorage: delete warehouse
  PostgresWarehouseStorage-->>WarehouseManagement: deletion result or conflict
Loading
Merge Risk: ⚪ Minimal · up to 79322

This change adds an opt-in policy for cancelling a queue's tasks when a warehouse is deleted. Default behavior is unchanged, and the supplied evidence shows no concrete merge-blocking risk.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 57.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 75 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
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.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly identifies the main change: task queues can cancel tasks during warehouse deletion. The visible ellipsis leaves the sentence incomplete, but the title remains specific and directly r…
Full details: Title check

Explanation

The title clearly identifies the main change: task queues can cancel tasks during warehouse deletion. The visible ellipsis leaves the sentence incomplete, but the title remains specific and directly related to the pull request.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

I’m a rabbit by the task queue gate,
I watch the warehouse tasks await.
Cancel queues clear their scheduled rows,
Blocking queues hold deletion close.
Old attempts stop; new runs stay,
I nibble clover and hop away.

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

coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 15, 2026
Extensions only return a variant from `TaskConfig::on_warehouse_delete`, which stays possible. Outside this crate a `match` needs a wildcard arm, so a later variant does not break downstream code.
coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 15, 2026
- Recording the outcome of a closed attempt stops after one try, with an info log. An attempt is closed when its task is gone (404), or when it already has an outcome (409 `TaskAttemptAlreadyCompleted` or `TaskAttemptAlreadyFailed`, for example after a cancel or a timeout). A 409 `TransactionFailed` still retries. `is_task_attempt_closed` exposes this decision for code that calls `CatalogTaskOps::record_task_*` in its own transaction.
- A late record of a closed attempt leaves a rescheduled task alone. Before, recording success after stop and "run now" deleted the rescheduled task when the caller committed (`record_success_in_transaction`).
- Docs: a warehouse with namespaces cannot be deleted, so the tasks a delete cancels belong to deleted entities. Tasks of a queue that is not registered block the delete.
- Test: a warehouse with a namespace keeps its tasks of `Cancel` queues.
coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 17, 2026
- The `OnWarehouseDelete::Cancel` doc states the general rule: a transaction that writes a row referencing the warehouse or locks one of its tasks, and then waits on another task of the warehouse, can deadlock with the delete; one side then fails with a retryable conflict.
- `queues_cancelled_on_warehouse_delete` matches on the variant, so a new variant needs a decision. Its sort keeps the order of cancelled queues the same across concurrent deletes.
- The test for built-in queues asserts the exact queue names.
@github-actions

Copy link
Copy Markdown
Contributor

✅ PR Title Formatted Correctly

The title of this PR match the correct format. Thank you!

@c-thiel
c-thiel enabled auto-merge (squash) October 17, 2026 20:15
@c-thiel
c-thiel merged commit 5355a1b into main Oct 17, 2026
78 checks passed
@c-thiel
c-thiel deleted the feat/task-entity-binding branch October 17, 2026 20:52
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