taskqx 0.7.1__tar.gz → 0.7.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. {taskqx-0.7.1 → taskqx-0.7.2}/.github/workflows/ci.yml +1 -1
  2. {taskqx-0.7.1 → taskqx-0.7.2}/CHANGELOG.md +8 -0
  3. {taskqx-0.7.1 → taskqx-0.7.2}/PKG-INFO +6 -4
  4. {taskqx-0.7.1 → taskqx-0.7.2}/README.md +5 -3
  5. {taskqx-0.7.1 → taskqx-0.7.2}/docs/operations.md +16 -1
  6. {taskqx-0.7.1 → taskqx-0.7.2}/pyproject.toml +1 -1
  7. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/__init__.py +2 -1
  8. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/redis.py +36 -2
  9. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/redis_admin.py +3 -0
  10. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/redis_calls.py +115 -28
  11. taskqx-0.7.2/src/taskqx/broker/redis_maintenance.py +276 -0
  12. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/redis_scripts.py +92 -11
  13. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/redis_state_machine.py +20 -1
  14. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/sqlite.py +33 -4
  15. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/sqlite_admin.py +2 -2
  16. taskqx-0.7.2/src/taskqx/broker/sqlite_maintenance.py +388 -0
  17. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/sqlite_state_machine.py +59 -17
  18. taskqx-0.7.2/src/taskqx/config.py +143 -0
  19. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/protocols.py +3 -0
  20. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/tui.py +1 -1
  21. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/types.py +1 -1
  22. taskqx-0.7.2/tests/test_auto_cleanup.py +458 -0
  23. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_redis_broker.py +129 -1
  24. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_redis_scripts.py +52 -4
  25. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_sqlite_broker.py +2 -1
  26. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_v06_interactive.py +17 -11
  27. {taskqx-0.7.1 → taskqx-0.7.2}/uv.lock +1 -1
  28. taskqx-0.7.1/src/taskqx/broker/redis_maintenance.py +0 -117
  29. taskqx-0.7.1/src/taskqx/broker/sqlite_maintenance.py +0 -218
  30. taskqx-0.7.1/src/taskqx/config.py +0 -57
  31. {taskqx-0.7.1 → taskqx-0.7.2}/.gitignore +0 -0
  32. {taskqx-0.7.1 → taskqx-0.7.2}/.python-version +0 -0
  33. {taskqx-0.7.1 → taskqx-0.7.2}/CONTRIBUTING.md +0 -0
  34. {taskqx-0.7.1 → taskqx-0.7.2}/LICENSE +0 -0
  35. {taskqx-0.7.1 → taskqx-0.7.2}/SECURITY.md +0 -0
  36. {taskqx-0.7.1 → taskqx-0.7.2}/benchmarks/v04_batch_submit.py +0 -0
  37. {taskqx-0.7.1 → taskqx-0.7.2}/benchmarks/v05_lifecycle.py +0 -0
  38. {taskqx-0.7.1 → taskqx-0.7.2}/docs/PRD.md +0 -0
  39. {taskqx-0.7.1 → taskqx-0.7.2}/docs/architecture.md +0 -0
  40. {taskqx-0.7.1 → taskqx-0.7.2}/docs/benchmark-v0.5.md +0 -0
  41. {taskqx-0.7.1 → taskqx-0.7.2}/docs/concepts.md +0 -0
  42. {taskqx-0.7.1 → taskqx-0.7.2}/docs/migration-v0.1-v0.2.md +0 -0
  43. {taskqx-0.7.1 → taskqx-0.7.2}/docs/migration-v0.2-v0.3.md +0 -0
  44. {taskqx-0.7.1 → taskqx-0.7.2}/docs/migration-v0.3-v0.4.md +0 -0
  45. {taskqx-0.7.1 → taskqx-0.7.2}/docs/migration-v0.4-v0.5.md +0 -0
  46. {taskqx-0.7.1 → taskqx-0.7.2}/docs/migration-v0.5-v0.6.md +0 -0
  47. {taskqx-0.7.1 → taskqx-0.7.2}/docs/migration-v0.6-v0.7.md +0 -0
  48. {taskqx-0.7.1 → taskqx-0.7.2}/docs/redis-backend.md +0 -0
  49. {taskqx-0.7.1 → taskqx-0.7.2}/docs/redis-lifecycle.md +0 -0
  50. {taskqx-0.7.1 → taskqx-0.7.2}/docs/roadmap.md +0 -0
  51. {taskqx-0.7.1 → taskqx-0.7.2}/docs/sqlite-backend.md +0 -0
  52. {taskqx-0.7.1 → taskqx-0.7.2}/docs/submission-and-dedup.md +0 -0
  53. {taskqx-0.7.1 → taskqx-0.7.2}/docs/v0.2-acceptance.md +0 -0
  54. {taskqx-0.7.1 → taskqx-0.7.2}/docs/v0.3-acceptance.md +0 -0
  55. {taskqx-0.7.1 → taskqx-0.7.2}/docs/v0.4-acceptance.md +0 -0
  56. {taskqx-0.7.1 → taskqx-0.7.2}/docs/v0.5-acceptance.md +0 -0
  57. {taskqx-0.7.1 → taskqx-0.7.2}/docs/v0.6-acceptance.md +0 -0
  58. {taskqx-0.7.1 → taskqx-0.7.2}/docs/v0.6-tui-cli.md +0 -0
  59. {taskqx-0.7.1 → taskqx-0.7.2}/docs/v0.7-development-plan.md +0 -0
  60. {taskqx-0.7.1 → taskqx-0.7.2}/docs/v0.7-rfc.md +0 -0
  61. {taskqx-0.7.1 → taskqx-0.7.2}/examples/01_sqlite_worker.py +0 -0
  62. {taskqx-0.7.1 → taskqx-0.7.2}/examples/02_redis_worker.py +0 -0
  63. {taskqx-0.7.1 → taskqx-0.7.2}/examples/03_retry_and_delay.py +0 -0
  64. {taskqx-0.7.1 → taskqx-0.7.2}/examples/04_batch_and_dedup.py +0 -0
  65. {taskqx-0.7.1 → taskqx-0.7.2}/examples/05_typed_payload.py +0 -0
  66. {taskqx-0.7.1 → taskqx-0.7.2}/examples/06_low_level_delivery.py +0 -0
  67. {taskqx-0.7.1 → taskqx-0.7.2}/examples/07_dlq_replay.py +0 -0
  68. {taskqx-0.7.1 → taskqx-0.7.2}/examples/08_health_and_consistency.py +0 -0
  69. {taskqx-0.7.1 → taskqx-0.7.2}/examples/09_scheduler.py +0 -0
  70. {taskqx-0.7.1 → taskqx-0.7.2}/examples/README.md +0 -0
  71. {taskqx-0.7.1 → taskqx-0.7.2}/main.py +0 -0
  72. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/__main__.py +0 -0
  73. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/admin.py +0 -0
  74. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/__init__.py +0 -0
  75. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/_time.py +0 -0
  76. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/redis_components.py +0 -0
  77. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/redis_observability.py +0 -0
  78. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/sqlite_components.py +0 -0
  79. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/broker/sqlite_migrations.py +0 -0
  80. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/capabilities.py +0 -0
  81. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/cli.py +0 -0
  82. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/consistency.py +0 -0
  83. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/errors.py +0 -0
  84. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/health.py +0 -0
  85. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/interactive.py +0 -0
  86. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/middleware.py +0 -0
  87. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/naming.py +0 -0
  88. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/observability.py +0 -0
  89. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/pagination.py +0 -0
  90. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/payloads.py +0 -0
  91. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/py.typed +0 -0
  92. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/retry.py +0 -0
  93. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/scheduler.py +0 -0
  94. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/serialization.py +0 -0
  95. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/shell.py +0 -0
  96. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/submission/__init__.py +0 -0
  97. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/submission/base.py +0 -0
  98. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/submission/observability.py +0 -0
  99. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/submission/redis.py +0 -0
  100. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/submission/routing.py +0 -0
  101. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/submission/service.py +0 -0
  102. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/submission/sqlite.py +0 -0
  103. {taskqx-0.7.1 → taskqx-0.7.2}/src/taskqx/worker.py +0 -0
  104. {taskqx-0.7.1 → taskqx-0.7.2}/tests/__init__.py +0 -0
  105. {taskqx-0.7.1 → taskqx-0.7.2}/tests/conformance/test_backend_v04.py +0 -0
  106. {taskqx-0.7.1 → taskqx-0.7.2}/tests/support.py +0 -0
  107. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_scheduler.py +0 -0
  108. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_v02_worker.py +0 -0
  109. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_v03_configuration.py +0 -0
  110. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_v04_batch_performance.py +0 -0
  111. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_v04_payloads.py +0 -0
  112. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_v04_replay_matrix.py +0 -0
  113. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_v05_consistency.py +0 -0
  114. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_v05_faults.py +0 -0
  115. {taskqx-0.7.1 → taskqx-0.7.2}/tests/test_v05_health.py +0 -0
@@ -22,7 +22,7 @@ jobs:
22
22
  - uses: actions/setup-python@v5
23
23
  with:
24
24
  python-version: ${{ matrix.python }}
25
- - run: uv sync --extra dev --extra redis --extra pydantic --locked
25
+ - run: uv sync --extra dev --extra redis --extra pydantic --extra tui --locked
26
26
  - run: uv run ruff check src tests
27
27
  - run: uv run mypy src tests
28
28
  - run: uv run pytest --cov=taskqx -q
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.2
4
+
5
+ - 新增终态消息自动清理能力([`AutoCleanupConfig`](src/taskqx/config.py) 默认开启):
6
+ - `ACKED` 默认在 5 分钟 tombstone 剪枝后于 1 小时后永久删除消息与索引(累计计数保留),支持 `acked_ttl=timedelta(0)` 立即删除及 `0 < acked_ttl <= ack_tombstone_ttl` 跳过剪枝直接删除。
7
+ - 支持在全局与单队列 `QueueConfig(auto_cleanup=...)` 按状态独立配置 `expired_ttl`、`dead_lettered_ttl` 或关闭清理,replay 后的消息自动清除清理标记。
8
+ - Redis 为已 ACK hash 设置原生 `PEXPIRE` 兜底,并在热路径按 `interval` 节流异步执行有界批量 `CLEANUP_TERMINAL`(`UNLINK` + `HDEL` + `LREM -1`);SQLite 在 `claim()` 内按 `interval` 节流执行有界批量删除,同时提供 `broker.cleanup()` 手动入口。
9
+ - 修复冒号持久名称校验测试(允许中间冒号、拒绝前导/纯冒号)与 CI `--extra tui` 依赖配置。
10
+
3
11
  ## 0.7.0.dev0 (unreleased)
4
12
 
5
13
  - 新增独立 `BackendScheduler` 与 broker `scheduler()`:在无 Worker、claim 或 inspect 活动时持续推进 DELAYED due、expiry、lease reclaim 和 ACK tombstone;多实例 tick 保持幂等,失败保留 traceback 并在后续 interval 重试。
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: taskqx
3
- Version: 0.7.1
3
+ Version: 0.7.2
4
4
  Summary: 异步优先的可靠任务消息框架
5
5
  License: MIT License
6
6
 
@@ -145,9 +145,11 @@ scheduler = broker.scheduler(interval=timedelta(seconds=1))
145
145
  await scheduler.run() # 在独立进程或服务任务中运行;取消或 close() 时退出
146
146
  ```
147
147
 
148
- ACK 会自动成为可查询的 tombstone,默认保留 5 分钟。可用 `QueueConfig(ack_tombstone_ttl=...)`
149
- 或 broker 的 `default_ack_tombstone_ttl=` 调整队列策略;不需要在每次 `submit()` 时传参。scheduler
150
- (或显式 `maintain()`)只会在 tombstone 到期后删除仍为 ACKED 的消息,累计计数不受影响。
148
+ ACK 会自动成为可查询的 tombstone,默认保留 5 分钟,随后在默认开启的 `AutoCleanupConfig` 下于
149
+ 1 小时后彻底清理消息记录与 Redis 索引(累计统计始终保留)。可通过 `QueueConfig(ack_tombstone_ttl=...)`、
150
+ `QueueConfig(auto_cleanup=...)` 或 broker 级 `auto_cleanup=AutoCleanupConfig(...)` 调整保留时长、
151
+ 扩展至 `expired_ttl` / `dead_lettered_ttl`、配置 `acked_ttl=timedelta(0)` 立即删除或关闭清理;
152
+ 也可按需调用 `await broker.cleanup()` 手动批量回收。
151
153
 
152
154
  `TaskMessage.clone()` 返回深拷贝、可提交的 `SubmitRequest` 草稿,不会复用来源 message ID、
153
155
  创建时间或投递状态。默认 `parent_id` 指向来源消息,dedup 三元组默认清除;传入
@@ -101,9 +101,11 @@ scheduler = broker.scheduler(interval=timedelta(seconds=1))
101
101
  await scheduler.run() # 在独立进程或服务任务中运行;取消或 close() 时退出
102
102
  ```
103
103
 
104
- ACK 会自动成为可查询的 tombstone,默认保留 5 分钟。可用 `QueueConfig(ack_tombstone_ttl=...)`
105
- 或 broker 的 `default_ack_tombstone_ttl=` 调整队列策略;不需要在每次 `submit()` 时传参。scheduler
106
- (或显式 `maintain()`)只会在 tombstone 到期后删除仍为 ACKED 的消息,累计计数不受影响。
104
+ ACK 会自动成为可查询的 tombstone,默认保留 5 分钟,随后在默认开启的 `AutoCleanupConfig` 下于
105
+ 1 小时后彻底清理消息记录与 Redis 索引(累计统计始终保留)。可通过 `QueueConfig(ack_tombstone_ttl=...)`、
106
+ `QueueConfig(auto_cleanup=...)` 或 broker 级 `auto_cleanup=AutoCleanupConfig(...)` 调整保留时长、
107
+ 扩展至 `expired_ttl` / `dead_lettered_ttl`、配置 `acked_ttl=timedelta(0)` 立即删除或关闭清理;
108
+ 也可按需调用 `await broker.cleanup()` 手动批量回收。
107
109
 
108
110
  `TaskMessage.clone()` 返回深拷贝、可提交的 `SubmitRequest` 草稿,不会复用来源 message ID、
109
111
  创建时间或投递状态。默认 `parent_id` 指向来源消息,dedup 三元组默认清除;传入
@@ -77,6 +77,21 @@ attempt、创建/确认时间、serializer、最后操作/原因或 workflow/par
77
77
  到期后 `inspect_message()`/`observe_message()` 返回 `None`,`list_message_summaries()` 和 TUI 仍能查询
78
78
  该轻量记录并明确显示 payload 已清除;因此 retention 到期前先导出所有需要用于排障或审计的业务内容。
79
79
 
80
+ 在 tombstone 之后,两个 backend 默认还启用 `AutoCleanupConfig` 自动彻底清理终态消息(包含 Redis hash、
81
+ `message-index` 以及 SQLite 对应记录),默认配置为 `enabled=True`、`acked_ttl=timedelta(hours=1)`、
82
+ `expired_ttl=None`、`dead_lettered_ttl=None`、`batch_size=100`、`interval=timedelta(seconds=5)`:
83
+
84
+ - **默认两阶段清理**:ACK 后 5 分钟剪枝业务 payload,1 小时后永久删除整条消息与索引;累计统计
85
+ (如 `acked_total`)始终保留。
86
+ - **可配置范围与立即清理**:可通过 `RedisBroker(..., auto_cleanup=AutoCleanupConfig(...))`、
87
+ `SQLiteBroker(..., auto_cleanup=...)` 或单队列 `QueueConfig(auto_cleanup=...)` 扩展到 `expired_ttl`
88
+ 与 `dead_lettered_ttl`,或将 `acked_ttl=timedelta(0)` 设为在 ACK 时直接删除;设置
89
+ `AutoCleanupConfig(enabled=False)` 可关闭默认清理。
90
+ - **零额外运维与热路径限流**:Redis 为 `ACKED` hash 自动设置原生 `PEXPIRE`,且 `claim()`/`finish()`
91
+ 热路径按 `interval` 节流触发非阻塞后台批量 Lua `UNLINK`(每次最多 `batch_size` 条),SQLite 则按
92
+ `interval` 在 `claim()` 内做有界批量删除;同时仍可通过 `await broker.cleanup(queue, limit=...)`
93
+ 或常驻 `BackendScheduler` 显式推进。
94
+
80
95
  `TaskMessage.clone()` 返回没有 message identity 或投递状态的深拷贝 `SubmitRequest` 草稿。它默认
81
96
  继承 queue、payload、metadata、workflow、expiry、max_attempts、剩余 delay 和 payload schema;
82
97
  默认以来源 ID 写入 `parent_id`,并清除 dedup key/scope/TTL。需要无 lineage 的重新提交时传入
@@ -135,7 +150,7 @@ taskqx --redis-url redis://127.0.0.1:6379/2 --namespace production redis migrate
135
150
  完整的开发与 release 验证需同时安装开发工具和 Redis backend:
136
151
 
137
152
  ```bash
138
- uv sync --extra dev --extra redis --extra pydantic --locked
153
+ uv sync --extra dev --extra redis --extra pydantic --extra tui --locked
139
154
  uv run ruff check src tests
140
155
  uv run mypy src tests
141
156
  uv run pytest --cov=taskqx -q
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taskqx"
3
- version = "0.7.1"
3
+ version = "0.7.2"
4
4
  description = "异步优先的可靠任务消息框架"
5
5
  readme = "README.md"
6
6
  license = {file = "LICENSE"}
@@ -8,7 +8,7 @@ from .broker import (
8
8
  SQLiteSubmissionStore,
9
9
  )
10
10
  from .capabilities import BackendCapabilities, DedupGuarantee, SubmissionCapabilities
11
- from .config import QueueConfig
11
+ from .config import AutoCleanupConfig, QueueConfig
12
12
  from .consistency import (
13
13
  ConsistencyIssue,
14
14
  ConsistencyReport,
@@ -58,6 +58,7 @@ from .types import (
58
58
  from .worker import TaskWorker
59
59
 
60
60
  __all__ = [
61
+ "AutoCleanupConfig",
61
62
  "BackendCapabilities",
62
63
  "BackendScheduler",
63
64
  "BatchSubmitItemResult",
@@ -14,7 +14,7 @@ from typing import Any, Literal, overload
14
14
  from typing_extensions import Self
15
15
 
16
16
  from ..capabilities import BackendCapabilities, SubmissionCapabilities
17
- from ..config import QueueConfig
17
+ from ..config import AutoCleanupConfig, QueueConfig
18
18
  from ..consistency import (
19
19
  ConsistencyIssue,
20
20
  ConsistencyReport,
@@ -132,6 +132,7 @@ class RedisBroker:
132
132
  consistency_pel_page_size: int = 1_000,
133
133
  queues: Mapping[str, QueueConfig] | None = None,
134
134
  default_ack_tombstone_ttl: timedelta = timedelta(minutes=5),
135
+ auto_cleanup: AutoCleanupConfig | None = None,
135
136
  event_sink: EventSink | None = None,
136
137
  events: EventSink | None = None,
137
138
  allow_legacy_names: bool = False,
@@ -153,6 +154,8 @@ class RedisBroker:
153
154
  or default_ack_tombstone_ttl.total_seconds() <= 0
154
155
  ):
155
156
  raise ValidationError("default_ack_tombstone_ttl 必须为正数 timedelta")
157
+ if auto_cleanup is not None and not isinstance(auto_cleanup, AutoCleanupConfig):
158
+ raise ValidationError("auto_cleanup 必须是 AutoCleanupConfig 或 None")
156
159
  validate_persistent_name(
157
160
  namespace, label="namespace", allow_legacy=allow_legacy_names
158
161
  )
@@ -166,6 +169,7 @@ class RedisBroker:
166
169
  max_attempts=default_max_attempts, default_dedup_ttl=default_dedup_ttl
167
170
  )
168
171
  self._default_ack_tombstone_ttl = default_ack_tombstone_ttl
172
+ self._default_auto_cleanup = auto_cleanup or AutoCleanupConfig()
169
173
  self._queues = dict(queues or {})
170
174
  for queue, config in self._queues.items():
171
175
  validate_persistent_name(
@@ -282,6 +286,14 @@ class RedisBroker:
282
286
  def _ack_tombstone_ttl(self, queue: str) -> timedelta:
283
287
  return self._queue_config(queue).ack_tombstone_ttl or self._default_ack_tombstone_ttl
284
288
 
289
+ def _auto_cleanup(self, queue: str) -> AutoCleanupConfig:
290
+ config = self._queue_config(queue).auto_cleanup
291
+ return self._default_auto_cleanup if config is None else config
292
+
293
+ def _cleanup_ttl_seconds(self, queue: str, status: MessageStatus) -> float:
294
+ ttl = self._auto_cleanup(queue).ttl_for(status)
295
+ return -1.0 if ttl is None else ttl.total_seconds()
296
+
285
297
  def _configure_submission_stores(
286
298
  self,
287
299
  submission_store: Any | None,
@@ -349,8 +361,9 @@ class RedisBroker:
349
361
  async def close(self) -> None:
350
362
  """关闭底层异步 Redis client。"""
351
363
  if not self._closed:
352
- await self._redis.aclose()
353
364
  self._closed = True
365
+ await self._maintenance.close()
366
+ await self._redis.aclose()
354
367
 
355
368
  def select_namespace(self, namespace: str) -> None:
356
369
  """Switch this broker's observation and operation namespace."""
@@ -640,6 +653,21 @@ class RedisBroker:
640
653
  await self._redis.hset(
641
654
  self._message_index_key(), prepared.message_id, prepared.queue
642
655
  )
656
+ if prepared.status == MessageStatus.EXPIRED.value:
657
+ expired_ttl = self._auto_cleanup(prepared.queue).ttl_for(
658
+ MessageStatus.EXPIRED
659
+ )
660
+ if expired_ttl is not None:
661
+ cleanup_at = _timestamp(prepared.created_at + expired_ttl)
662
+ await self._redis.hset(
663
+ self._message_key(prepared.queue, prepared.message_id),
664
+ "cleanup_at",
665
+ str(cleanup_at),
666
+ )
667
+ await self._redis.zadd(
668
+ self._queue_key(prepared.queue, "cleanup:expired"),
669
+ {prepared.message_id: cleanup_at},
670
+ )
643
671
  await self._submission_observer.record(prepared, message, result)
644
672
 
645
673
  def _reconstruct_replay_message(
@@ -841,6 +869,12 @@ class RedisBroker:
841
869
  """回收已到期租约,并把 READY/LEASED 的过期消息移入 EQ。"""
842
870
  return await self._maintenance.run(queue)
843
871
 
872
+ async def cleanup(
873
+ self, queue: str | None = None, *, limit: int | None = None
874
+ ) -> int:
875
+ """按配置的保留策略批量清理已到期的终态消息。"""
876
+ return await self._maintenance.cleanup(queue, limit=limit)
877
+
844
878
  async def inspect(self, queue: str) -> QueueStats:
845
879
  """读取队列实时计数与累计计数。"""
846
880
  await self.maintain(queue)
@@ -196,6 +196,9 @@ class RedisAdmin:
196
196
  "eq",
197
197
  "stats",
198
198
  "retention",
199
+ "cleanup:acked",
200
+ "cleanup:expired",
201
+ "cleanup:dead_lettered",
199
202
  )
200
203
  ]
201
204
  keys = [
@@ -8,15 +8,18 @@ be asserted without a Redis server.
8
8
  from __future__ import annotations
9
9
 
10
10
  import base64
11
+ from collections.abc import Sequence
11
12
  from dataclasses import dataclass
12
13
  from typing import Any, Protocol
13
14
 
14
15
  from ..submission.base import PreparedSubmission
16
+ from ..types import MessageStatus
15
17
  from ._time import timestamp as _timestamp
16
18
  from .redis_scripts import (
17
19
  BATCH_SUBMIT,
18
20
  CLAIM,
19
21
  CLEANUP_ACKED,
22
+ CLEANUP_TERMINAL,
20
23
  DUE_DELAYED,
21
24
  EXPIRE,
22
25
  EXTEND_LEASE,
@@ -118,6 +121,7 @@ def claim_call(
118
121
  token: str,
119
122
  lease_until: float,
120
123
  entry_id: str,
124
+ expired_cleanup_ttl: float = -1.0,
121
125
  ) -> RedisScriptCall:
122
126
  return RedisScriptCall(
123
127
  CLAIM,
@@ -128,6 +132,7 @@ def claim_call(
128
132
  backend._queue_key(queue, "expiry"),
129
133
  backend._queue_key(queue, "stream"),
130
134
  backend._queue_key(queue, "ready"),
135
+ backend._queue_key(queue, "cleanup:expired"),
131
136
  ),
132
137
  (
133
138
  str(now),
@@ -138,6 +143,7 @@ def claim_call(
138
143
  str(lease_until),
139
144
  backend._group_name(),
140
145
  entry_id,
146
+ str(expired_cleanup_ttl),
141
147
  ),
142
148
  )
143
149
 
@@ -156,25 +162,34 @@ def finish_call(
156
162
  retry_available_at: float | None,
157
163
  max_attempts: int | None,
158
164
  ack_tombstone_ttl: float,
165
+ acked_cleanup_ttl: float = -1.0,
166
+ expired_cleanup_ttl: float = -1.0,
167
+ dead_lettered_cleanup_ttl: float = -1.0,
159
168
  ) -> RedisScriptCall:
160
169
  return RedisScriptCall(
161
170
  FINISH,
162
- tuple(
163
- backend._queue_key(queue, kind)
164
- if kind != "message"
165
- else backend._message_key(queue, message_id)
166
- for kind in (
167
- "message",
168
- "leases",
169
- "expiry",
170
- "stream",
171
- "eq",
172
- "stats",
173
- "dlq",
174
- "ready",
175
- "delayed",
176
- "retention",
177
- )
171
+ (
172
+ *(
173
+ backend._queue_key(queue, kind)
174
+ if kind != "message"
175
+ else backend._message_key(queue, message_id)
176
+ for kind in (
177
+ "message",
178
+ "leases",
179
+ "expiry",
180
+ "stream",
181
+ "eq",
182
+ "stats",
183
+ "dlq",
184
+ "ready",
185
+ "delayed",
186
+ "retention",
187
+ "cleanup:acked",
188
+ "cleanup:expired",
189
+ "cleanup:dead_lettered",
190
+ )
191
+ ),
192
+ backend._message_index_key(),
178
193
  ),
179
194
  (
180
195
  action,
@@ -188,6 +203,9 @@ def finish_call(
188
203
  str(retry_available_at) if retry_available_at is not None else "0",
189
204
  str(max_attempts or 0),
190
205
  str(ack_tombstone_ttl),
206
+ str(acked_cleanup_ttl),
207
+ str(expired_cleanup_ttl),
208
+ str(dead_lettered_cleanup_ttl),
191
209
  ),
192
210
  )
193
211
 
@@ -200,6 +218,7 @@ def extend_lease_call(
200
218
  delivery_id: str,
201
219
  token: str,
202
220
  lease_until: float,
221
+ expired_cleanup_ttl: float = -1.0,
203
222
  ) -> RedisScriptCall:
204
223
  return RedisScriptCall(
205
224
  EXTEND_LEASE,
@@ -209,8 +228,16 @@ def extend_lease_call(
209
228
  backend._queue_key(queue, "stream"),
210
229
  backend._queue_key(queue, "expiry"),
211
230
  backend._queue_key(queue, "eq"),
231
+ backend._queue_key(queue, "cleanup:expired"),
232
+ ),
233
+ (
234
+ delivery_id,
235
+ token,
236
+ str(lease_until),
237
+ message_id,
238
+ backend._group_name(),
239
+ str(expired_cleanup_ttl),
212
240
  ),
213
- (delivery_id, token, str(lease_until), message_id, backend._group_name()),
214
241
  )
215
242
 
216
243
 
@@ -229,7 +256,12 @@ def pel_recover_call(
229
256
 
230
257
 
231
258
  def due_delayed_call(
232
- backend: RedisKeyspace, *, queue: str, message_id: str, now: float
259
+ backend: RedisKeyspace,
260
+ *,
261
+ queue: str,
262
+ message_id: str,
263
+ now: float,
264
+ expired_cleanup_ttl: float = -1.0,
233
265
  ) -> RedisScriptCall:
234
266
  return RedisScriptCall(
235
267
  DUE_DELAYED,
@@ -237,14 +269,27 @@ def due_delayed_call(
237
269
  backend._queue_key(queue, kind)
238
270
  if kind != "message"
239
271
  else backend._message_key(queue, message_id)
240
- for kind in ("message", "delayed", "ready", "stream", "eq", "expiry")
272
+ for kind in (
273
+ "message",
274
+ "delayed",
275
+ "ready",
276
+ "stream",
277
+ "eq",
278
+ "expiry",
279
+ "cleanup:expired",
280
+ )
241
281
  ),
242
- (str(now), message_id),
282
+ (str(now), message_id, str(expired_cleanup_ttl)),
243
283
  )
244
284
 
245
285
 
246
286
  def expire_call(
247
- backend: RedisKeyspace, *, queue: str, message_id: str, now: float
287
+ backend: RedisKeyspace,
288
+ *,
289
+ queue: str,
290
+ message_id: str,
291
+ now: float,
292
+ expired_cleanup_ttl: float = -1.0,
248
293
  ) -> RedisScriptCall:
249
294
  return RedisScriptCall(
250
295
  EXPIRE,
@@ -260,14 +305,21 @@ def expire_call(
260
305
  "eq",
261
306
  "ready",
262
307
  "delayed",
308
+ "cleanup:expired",
263
309
  )
264
310
  ),
265
- (str(now), backend._group_name(), message_id),
311
+ (str(now), backend._group_name(), message_id, str(expired_cleanup_ttl)),
266
312
  )
267
313
 
268
314
 
269
315
  def reclaim_lease_call(
270
- backend: RedisKeyspace, *, queue: str, message_id: str, now: float
316
+ backend: RedisKeyspace,
317
+ *,
318
+ queue: str,
319
+ message_id: str,
320
+ now: float,
321
+ expired_cleanup_ttl: float = -1.0,
322
+ dead_lettered_cleanup_ttl: float = -1.0,
271
323
  ) -> RedisScriptCall:
272
324
  return RedisScriptCall(
273
325
  RECLAIM_LEASE,
@@ -284,9 +336,17 @@ def reclaim_lease_call(
284
336
  "stats",
285
337
  "eq",
286
338
  "ready",
339
+ "cleanup:expired",
340
+ "cleanup:dead_lettered",
287
341
  )
288
342
  ),
289
- (str(now), backend._group_name(), message_id),
343
+ (
344
+ str(now),
345
+ backend._group_name(),
346
+ message_id,
347
+ str(expired_cleanup_ttl),
348
+ str(dead_lettered_cleanup_ttl),
349
+ ),
290
350
  )
291
351
 
292
352
 
@@ -305,6 +365,33 @@ def cleanup_acked_call(
305
365
  )
306
366
 
307
367
 
368
+ def cleanup_terminal_call(
369
+ backend: RedisKeyspace,
370
+ *,
371
+ queue: str,
372
+ status: MessageStatus,
373
+ message_ids: Sequence[str],
374
+ now: float,
375
+ ) -> RedisScriptCall:
376
+ """Build batched permanent cleanup for due terminal messages of one status."""
377
+
378
+ audit_kind = {
379
+ MessageStatus.DEAD_LETTERED: "dlq",
380
+ MessageStatus.EXPIRED: "eq",
381
+ }.get(status)
382
+ return RedisScriptCall(
383
+ CLEANUP_TERMINAL,
384
+ (
385
+ backend._queue_key(queue, f"cleanup:{status.value}"),
386
+ backend._queue_key(queue, "retention"),
387
+ backend._queue_key(queue, audit_kind) if audit_kind is not None else "",
388
+ backend._message_index_key(),
389
+ *(backend._message_key(queue, message_id) for message_id in message_ids),
390
+ ),
391
+ (str(now), status.value, *message_ids),
392
+ )
393
+
394
+
308
395
  def replay_dead_letter_call(
309
396
  backend: RedisKeyspace,
310
397
  *,
@@ -332,8 +419,8 @@ def replay_dead_letter_call(
332
419
  new_dedup_key,
333
420
  backend._message_key(target_queue, message_id),
334
421
  backend._message_index_key(),
335
- )
336
- ,
422
+ backend._queue_key(source_queue, "cleanup:dead_lettered"),
423
+ ),
337
424
  (
338
425
  message_id,
339
426
  envelope,
@@ -373,8 +460,8 @@ def replay_expired_call(
373
460
  new_dedup_key,
374
461
  backend._message_key(target_queue, message_id),
375
462
  backend._message_index_key(),
376
- )
377
- ,
463
+ backend._queue_key(source_queue, "cleanup:expired"),
464
+ ),
378
465
  (
379
466
  message_id,
380
467
  envelope,