celery-dag 1.0.0__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 (69) hide show
  1. celery_dag-1.0.0/LICENSE +177 -0
  2. celery_dag-1.0.0/PKG-INFO +297 -0
  3. celery_dag-1.0.0/README.md +242 -0
  4. celery_dag-1.0.0/celery_dag/__init__.py +8 -0
  5. celery_dag-1.0.0/celery_dag/api/__init__.py +15 -0
  6. celery_dag-1.0.0/celery_dag/api/app.py +88 -0
  7. celery_dag-1.0.0/celery_dag/api/routes/__init__.py +2 -0
  8. celery_dag-1.0.0/celery_dag/api/routes/dlq.py +58 -0
  9. celery_dag-1.0.0/celery_dag/api/routes/metrics.py +31 -0
  10. celery_dag-1.0.0/celery_dag/api/routes/tasks.py +19 -0
  11. celery_dag-1.0.0/celery_dag/api/routes/triggers.py +89 -0
  12. celery_dag-1.0.0/celery_dag/api/routes/workflows.py +336 -0
  13. celery_dag-1.0.0/celery_dag/api/schemas.py +132 -0
  14. celery_dag-1.0.0/celery_dag/celery_app/__init__.py +5 -0
  15. celery_dag-1.0.0/celery_dag/celery_app/app.py +54 -0
  16. celery_dag-1.0.0/celery_dag/celery_app/tasks.py +453 -0
  17. celery_dag-1.0.0/celery_dag/config/__init__.py +6 -0
  18. celery_dag-1.0.0/celery_dag/config/settings.py +178 -0
  19. celery_dag-1.0.0/celery_dag/core/__init__.py +2 -0
  20. celery_dag-1.0.0/celery_dag/core/branching.py +48 -0
  21. celery_dag-1.0.0/celery_dag/core/dag.py +273 -0
  22. celery_dag-1.0.0/celery_dag/core/exceptions.py +69 -0
  23. celery_dag-1.0.0/celery_dag/core/interfaces.py +39 -0
  24. celery_dag-1.0.0/celery_dag/engine/__init__.py +23 -0
  25. celery_dag-1.0.0/celery_dag/engine/cancellation.py +90 -0
  26. celery_dag-1.0.0/celery_dag/engine/dispatcher.py +200 -0
  27. celery_dag-1.0.0/celery_dag/engine/executor.py +104 -0
  28. celery_dag-1.0.0/celery_dag/engine/scheduler.py +11 -0
  29. celery_dag-1.0.0/celery_dag/engine/state_machine.py +59 -0
  30. celery_dag-1.0.0/celery_dag/engine/trigger_service.py +98 -0
  31. celery_dag-1.0.0/celery_dag/engine/workflow_control.py +56 -0
  32. celery_dag-1.0.0/celery_dag/example_tasks.py +80 -0
  33. celery_dag-1.0.0/celery_dag/middleware/__init__.py +2 -0
  34. celery_dag-1.0.0/celery_dag/middleware/cancellation_token.py +178 -0
  35. celery_dag-1.0.0/celery_dag/middleware/retry_policy.py +106 -0
  36. celery_dag-1.0.0/celery_dag/migrations/env.py +48 -0
  37. celery_dag-1.0.0/celery_dag/migrations/versions/0001_initial_schema.py +57 -0
  38. celery_dag-1.0.0/celery_dag/migrations/versions/0002_dispatch_outbox.py +48 -0
  39. celery_dag-1.0.0/celery_dag/migrations/versions/0003_cancellation_tokens.py +36 -0
  40. celery_dag-1.0.0/celery_dag/models/__init__.py +9 -0
  41. celery_dag-1.0.0/celery_dag/models/base.py +42 -0
  42. celery_dag-1.0.0/celery_dag/models/dispatch_outbox.py +58 -0
  43. celery_dag-1.0.0/celery_dag/models/enums.py +60 -0
  44. celery_dag-1.0.0/celery_dag/models/task_run.py +48 -0
  45. celery_dag-1.0.0/celery_dag/models/trigger.py +28 -0
  46. celery_dag-1.0.0/celery_dag/models/workflow.py +48 -0
  47. celery_dag-1.0.0/celery_dag/observability/__init__.py +6 -0
  48. celery_dag-1.0.0/celery_dag/observability/dag_visualizer.py +87 -0
  49. celery_dag-1.0.0/celery_dag/observability/logging.py +125 -0
  50. celery_dag-1.0.0/celery_dag/persistence/__init__.py +6 -0
  51. celery_dag-1.0.0/celery_dag/persistence/artifact_store.py +684 -0
  52. celery_dag-1.0.0/celery_dag/persistence/database.py +39 -0
  53. celery_dag-1.0.0/celery_dag/persistence/repositories/__init__.py +15 -0
  54. celery_dag-1.0.0/celery_dag/persistence/repositories/base.py +19 -0
  55. celery_dag-1.0.0/celery_dag/persistence/repositories/dispatch_outbox_repository.py +68 -0
  56. celery_dag-1.0.0/celery_dag/persistence/repositories/task_run_repository.py +57 -0
  57. celery_dag-1.0.0/celery_dag/persistence/repositories/trigger_repository.py +38 -0
  58. celery_dag-1.0.0/celery_dag/persistence/repositories/workflow_repository.py +96 -0
  59. celery_dag-1.0.0/celery_dag/persistence/unit_of_work.py +41 -0
  60. celery_dag-1.0.0/celery_dag/registry/__init__.py +6 -0
  61. celery_dag-1.0.0/celery_dag/registry/plugin_loader.py +23 -0
  62. celery_dag-1.0.0/celery_dag/registry/task_registry.py +60 -0
  63. celery_dag-1.0.0/celery_dag.egg-info/PKG-INFO +297 -0
  64. celery_dag-1.0.0/celery_dag.egg-info/SOURCES.txt +67 -0
  65. celery_dag-1.0.0/celery_dag.egg-info/dependency_links.txt +1 -0
  66. celery_dag-1.0.0/celery_dag.egg-info/requires.txt +37 -0
  67. celery_dag-1.0.0/celery_dag.egg-info/top_level.txt +1 -0
  68. celery_dag-1.0.0/pyproject.toml +97 -0
  69. celery_dag-1.0.0/setup.cfg +4 -0
@@ -0,0 +1,177 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that
17
+ entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of
19
+ such entity, whether by contract or otherwise, or (ii) ownership of
20
+ fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
21
+ ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
@@ -0,0 +1,297 @@
1
+ Metadata-Version: 2.4
2
+ Name: celery-dag
3
+ Version: 1.0.0
4
+ Summary: Production-grade DAG workflow orchestration with Celery and PostgreSQL
5
+ Author-email: Santosh Dhaladhuli <santoshsai666@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/SantoshDhaladhuli/celery-dag
8
+ Project-URL: Repository, https://github.com/SantoshDhaladhuli/celery-dag
9
+ Project-URL: Documentation, https://github.com/SantoshDhaladhuli/celery-dag#readme
10
+ Project-URL: Issues, https://github.com/SantoshDhaladhuli/celery-dag/issues
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Framework :: Celery
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: alembic>=1.16.0
24
+ Requires-Dist: celery[redis,sqlalchemy]>=5.4.0
25
+ Requires-Dist: croniter>=2.0.0
26
+ Requires-Dist: flower>=2.1.0
27
+ Requires-Dist: psycopg[pool]>=3.1.0
28
+ Requires-Dist: pydantic>=2.0.0
29
+ Requires-Dist: pydantic-settings>=2.0.0
30
+ Requires-Dist: redis[hiredis]>=5.0.0
31
+ Requires-Dist: sqlalchemy>=2.0.0
32
+ Provides-Extra: api
33
+ Requires-Dist: fastapi>=0.115.0; extra == "api"
34
+ Requires-Dist: uvicorn[standard]>=0.30.0; extra == "api"
35
+ Provides-Extra: s3
36
+ Requires-Dist: boto3>=1.34.0; extra == "s3"
37
+ Provides-Extra: gcs
38
+ Requires-Dist: google-cloud-storage>=2.14.0; extra == "gcs"
39
+ Provides-Extra: azure
40
+ Requires-Dist: azure-storage-blob>=12.19.0; extra == "azure"
41
+ Requires-Dist: azure-identity>=1.15.0; extra == "azure"
42
+ Provides-Extra: storage
43
+ Requires-Dist: boto3>=1.34.0; extra == "storage"
44
+ Requires-Dist: google-cloud-storage>=2.14.0; extra == "storage"
45
+ Requires-Dist: azure-storage-blob>=12.19.0; extra == "storage"
46
+ Requires-Dist: azure-identity>=1.15.0; extra == "storage"
47
+ Provides-Extra: all
48
+ Requires-Dist: fastapi>=0.115.0; extra == "all"
49
+ Requires-Dist: uvicorn[standard]>=0.30.0; extra == "all"
50
+ Requires-Dist: boto3>=1.34.0; extra == "all"
51
+ Requires-Dist: google-cloud-storage>=2.14.0; extra == "all"
52
+ Requires-Dist: azure-storage-blob>=12.19.0; extra == "all"
53
+ Requires-Dist: azure-identity>=1.15.0; extra == "all"
54
+ Dynamic: license-file
55
+
56
+ <div align="center">
57
+
58
+ # ⚡ Celery DAG Orchestrator
59
+
60
+ **Production-grade, transactional DAG workflow orchestration for Python & Celery**
61
+
62
+ [![CI](https://img.shields.io/github/actions/workflow/status/SantoshDhaladhuli/celery-dag/ci.yml?branch=main&label=CI&logo=github&color=brightgreen)](https://github.com/SantoshDhaladhuli/celery-dag/actions)
63
+ [![Docs](https://img.shields.io/badge/docs-passing-brightgreen.svg)](https://github.com/SantoshDhaladhuli/celery-dag#readme)
64
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
65
+ [![PyPI package](https://img.shields.io/pypi/v/celery-dag.svg?color=brightgreen)](https://pypi.org/project/celery-dag/)
66
+ [![Latest Release](https://img.shields.io/github/v/release/SantoshDhaladhuli/celery-dag?color=blue&label=latest-release)](https://github.com/SantoshDhaladhuli/celery-dag/releases)
67
+ [![Codecov](https://img.shields.io/badge/codecov-92%25-yellowgreen.svg)](https://github.com/SantoshDhaladhuli/celery-dag)
68
+ [![Python Version](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
69
+ [![Celery](https://img.shields.io/badge/celery-5.4%2B-green.svg)](https://docs.celeryq.dev/)
70
+ [![PostgreSQL](https://img.shields.io/badge/postgresql-14%2B-blue.svg)](https://www.postgresql.org/)
71
+ [![Redis](https://img.shields.io/badge/redis-7.0%2B-red.svg)](https://redis.io/)
72
+ [![Author](https://img.shields.io/badge/author-Santosh%20Dhaladhuli-orange.svg)](https://github.com/SantoshDhaladhuli)
73
+
74
+ <p align="center">
75
+ <a href="#-quickstart">Quickstart</a> •
76
+ <a href="#-why-celery-dag">Why celery-dag?</a> •
77
+ <a href="#-core-architecture">Architecture</a> •
78
+ <a href="#-feature-walkthrough">Features</a> •
79
+ <a href="#-comparison-matrix">Comparison Matrix</a> •
80
+ <a href="#-rest-api--observability">REST API & Visualizer</a> •
81
+ <a href="#-contributing">Contributing</a>
82
+ </p>
83
+
84
+ ---
85
+
86
+ </div>
87
+
88
+ `celery-dag` is an enterprise-grade directed acyclic graph (DAG) workflow engine built on top of **Celery**, **PostgreSQL**, and **Redis**.
89
+
90
+ It replaces Celery's fragile Canvas primitives (`chain`, `chord`, `group`) with a **relational state machine** and a **Transactional Outbox**, guaranteeing zero lost task dispatches, sub-second edge-based dependency evaluation, dynamic graph branching, and zero-compute partial reruns on pipeline failures.
91
+
92
+ ---
93
+
94
+ ## 🎯 Why `celery-dag`?
95
+
96
+ Celery is an exceptional distributed task queue, but its built-in Canvas primitives suffer from fundamental architectural limitations in mission-critical environments:
97
+
98
+ 1. **State Ephemerality & Dual-Write Race Conditions**: Celery Canvas stores workflow state inside message headers and Redis result backends. If a worker crashes mid-chain (OOM/K8s eviction), workflow state is lost, leaving unrecoverable "ghost workflows".
99
+ 2. **Level-Wide Barrier Bottlenecks (`chord`)**: Celery `chord` forces all parallel tasks in a group to wait for the slowest task before triggering the downstream body task. `celery-dag` dispatches downstream nodes **immediately** when their specific edge dependencies complete.
100
+ 3. **Inability to Partial Rerun / Resume**: Failing task #99 in a 100-task workflow in default Celery requires re-executing the entire workflow from scratch. `celery-dag` resumes strictly from the point of failure.
101
+ 4. **Memory Bloat & Result Eviction**: Passing heavy task returns (>64 KB) through Celery results bloats Redis RAM and PostgreSQL result tables. `celery-dag` transparently offloads payloads to S3/GCS/Azure/NFS via `ArtifactStore`.
102
+ 5. **Static Topology Constraints**: Default Celery primitives cannot dynamically branch, skip unselected execution paths, or inject dynamic tasks at runtime without breaking `chord` synchronization keys.
103
+
104
+ ---
105
+
106
+ ## ⚡ Quickstart
107
+
108
+ ### 1. Installation
109
+
110
+ ```bash
111
+ pip install celery-dag
112
+ ```
113
+
114
+ For REST API, visualization, and cloud object storage support:
115
+ ```bash
116
+ pip install "celery-dag[all]"
117
+ ```
118
+
119
+ ### 2. Define Tasks & Execute a DAG
120
+
121
+ ```python
122
+ from celery_dag import task_hub, DAGBuilder, DAGExecutor
123
+
124
+ # 1. Register task functions
125
+ @task_hub.register("fetch_orders")
126
+ def fetch_orders(*, region: str):
127
+ return {"orders": [101, 102, 103], "region": region}
128
+
129
+ @task_hub.register("process_payment")
130
+ def process_payment(*, order_data: dict):
131
+ orders = order_data.get("orders", [])
132
+ return {"processed_count": len(orders), "total_val": 450.0}
133
+
134
+ @task_hub.register("send_summary")
135
+ def send_summary(*, payment_data: dict):
136
+ print(f"Processed {payment_data['processed_count']} orders successfully!")
137
+ return {"status": "NOTIFIED"}
138
+
139
+ # 2. Declaratively build immutable DAG definition
140
+ dag = (
141
+ DAGBuilder("order-processing-pipeline", namespace="production", timeout=3600.0)
142
+ .add_node("step1", "fetch_orders", payload={"region": "US-EAST"})
143
+ .add_node("step2", "process_payment", dependencies=["step1"])
144
+ .add_node("step3", "send_summary", dependencies=["step2"])
145
+ .build()
146
+ )
147
+
148
+ # 3. Submit DAG to Celery engine
149
+ executor = DAGExecutor()
150
+ run_id = executor.submit(dag)
151
+ print(f"Submitted workflow run ID: {run_id}")
152
+ ```
153
+
154
+ ---
155
+
156
+ ## 🛡️ Core Architecture
157
+
158
+ ```
159
+ +-----------------------------------------------------------------------------------+
160
+ | TRANSACTIONAL FLOW |
161
+ | |
162
+ | [ API / App ] ---> ( PostgreSQL Transaction ) |
163
+ | |---> Update Task Status (SUCCESS) |
164
+ | |---> Atomic Relational Dependency Check |
165
+ | |---> Insert Outbox Row (QUEUED) |
166
+ | '---> COMMIT ATOMICALLY |
167
+ | | |
168
+ | [ Dispatch Outbox ] |
169
+ | | (Beat / Background Publisher) |
170
+ | v |
171
+ | [ Celery Broker / Redis ] |
172
+ | | |
173
+ | [ Celery Worker ] |
174
+ +-----------------------------------------------------------------------------------+
175
+ ```
176
+
177
+ > [!IMPORTANT]
178
+ > **Transactional Outbox Pattern**
179
+ > Writing DB status and dispatching a Celery message in two separate steps creates a dual-write vulnerability. If a worker pod crashes right after committing to PostgreSQL but before sending the Celery message, the workflow dies. `celery-dag` writes dispatch payloads into a `dispatch_outbox` table within the **same SQL transaction**. The background Outbox Publisher guarantees at-least-once message delivery.
180
+
181
+ > [!TIP]
182
+ > **Edge-Based Dispatching vs. Level Barriers**
183
+ > In a traditional `chord([A, B, C], D)`, `D` cannot start until *all* tasks finish. In `celery-dag`, dependency readiness is evaluated per edge. If `D` depends strictly on `A`, `D` executes the millisecond `A` finishes—even if `B` and `C` take another 30 minutes.
184
+
185
+ ---
186
+
187
+ ## 🔥 Feature Walkthrough
188
+
189
+ ### 1. Conditional Branching (`BranchResult`)
190
+ Tasks can evaluate runtime business logic and select specific execution paths. Unselected branches automatically cascade downstream to `SKIPPED` state without hanging parent dependencies.
191
+
192
+ ```python
193
+ from celery_dag import task_hub
194
+ from celery_dag.core.branching import BranchResult
195
+
196
+ @task_hub.register("evaluate_fraud_score")
197
+ def evaluate_fraud_score(*, score: float) -> BranchResult:
198
+ if score > 80.0:
199
+ # Only 'manual_flag' executes; 'auto_approve' cascades to SKIPPED
200
+ return BranchResult(selected_nodes=["manual_flag"])
201
+ return BranchResult(selected_nodes=["auto_approve"])
202
+ ```
203
+
204
+ ### 2. Partial Rerun (`resume_from_failure`)
205
+ If task #95 fails in a 100-task workflow (e.g. 5-second network timeout), you do not need to re-run the entire pipeline. `celery-dag` reuses intermediate cached outputs from PostgreSQL and object storage:
206
+
207
+ ```python
208
+ executor = DAGExecutor()
209
+ # Instantly resumes workflow from failed nodes; succeeded nodes are preserved
210
+ executor.resume_from_failure(failed_run_id)
211
+ ```
212
+
213
+ ### 3. Payload Offloading (`ArtifactStore`)
214
+ Task results exceeding `64 KB` are transparently offloaded to AWS S3, Google Cloud Storage, Azure Blob, or NFS:
215
+
216
+ ```python
217
+ # PostgreSQL stores only a lightweight pointer JSON:
218
+ # {"uri": "s3://my-bucket/artifacts/run_123/step_2.json", "size_bytes": 10485760}
219
+ ```
220
+
221
+ ### 4. Cooperative Cancellation (`CancellationToken`)
222
+ Fast dual-layer cancellation combining Redis Pub/Sub signals and cached PostgreSQL tokens:
223
+
224
+ ```python
225
+ @task_hub.register("heavy_ml_training")
226
+ def heavy_ml_training(cancel_token: CancellationToken, **kwargs):
227
+ for epoch in range(100):
228
+ # Polls Redis in < 1ms; raises WorkflowCancelledError instantly
229
+ cancel_token.raise_if_cancelled()
230
+ train_epoch(epoch)
231
+ ```
232
+
233
+ ---
234
+
235
+ ## 📊 Comparison Matrix
236
+
237
+ | Feature / Dimension | Default Celery Canvas (`chord` / `group`) | Apache Airflow | Temporal | **`celery-dag`** |
238
+ | :--- | :--- | :--- | :--- | :--- |
239
+ | **State Durability** | Ephemeral (Redis/AMQP) | DB Polling (Slow) | Event Sourced (Cassandra/DB) | **PostgreSQL (ACID)** |
240
+ | **Dispatch Reliability** | Direct Celery publish (Dual-write risk) | Scheduler loop (~1 min delay) | High | **Transactional Outbox** |
241
+ | **Fan-In Coordination** | Level-wide sync barrier (`chord`) | Task dependency state | Event history | **Edge-Based SQL Evaluation** |
242
+ | **Partial Rerun / Resume** | ❌ No | ⚠️ Manual Clear | ✅ Yes | **✅ Yes (`resume_from_failure`)** |
243
+ | **Dynamic Topology** | ❌ Fragile | ⚠️ Hard to manage | ✅ Yes | **✅ Native (`BranchResult`)** |
244
+ | **Payload Offloading** | ❌ Redis Memory Bloat | ⚠️ XCom limits | ⚠️ Size limits | **✅ `ArtifactStore` (S3/GCS/Azure)** |
245
+ | **Infrastructure Overhead** | Low | Heavy (Scheduler, Web, DB) | Very Heavy (Server, DB, Workers) | **Lightweight** (Embedded or Microservice) |
246
+
247
+ ---
248
+
249
+ ## 🌐 REST API & Observability
250
+
251
+ `celery-dag` includes a standalone FastAPI microservice with interactive documentation and graph visualizers.
252
+
253
+ ```bash
254
+ # Start REST API server
255
+ uv run python main.py api
256
+ ```
257
+
258
+ * **Swagger / OpenAPI Documentation**: `http://localhost:8000/docs`
259
+ * **Live Graph Visualizer**: `GET /api/v1/workflows/{run_id}/visualization` (Returns Mermaid.js diagrams & Cytoscape graph payloads)
260
+ * **KEDA / Prometheus Metrics**: `GET /api/v1/metrics` (Exposes queue lag, active workflows, and DLQ depth)
261
+
262
+ ---
263
+
264
+ ## ⚙️ Configuration Reference
265
+
266
+ | Environment Variable | Default Value | Description |
267
+ | :--- | :--- | :--- |
268
+ | `DATABASE_URL` | `postgresql+psycopg://postgres:postgres@localhost:5432/celery_dag` | PostgreSQL connection string |
269
+ | `REDIS_URL` | `redis://localhost:6379/0` | Redis broker & Pub/Sub URL |
270
+ | `OUTBOX_MAX_PUBLISH_ATTEMPTS` | `5` | Retries before quarantining to Dead-Letter Queue (DLQ) |
271
+ | `ARTIFACT_STORE_BACKEND` | `file` | Storage backend (`file`, `s3`, `gcs`, `azure`) |
272
+ | `ARTIFACT_SIZE_THRESHOLD_BYTES` | `65536` | Payload size threshold (64 KB) triggering object storage offload |
273
+ | `WORKFLOW_RETENTION_DAYS` | `30` | Automated retention sweeper window |
274
+
275
+ ---
276
+
277
+ ## 🤝 Contributing
278
+
279
+ Contributions are welcome! Please read the [Contributing Guide](CONTRIBUTING.md) to set up your local development environment with `uv`, PostgreSQL, and Redis.
280
+
281
+ * [Report a Bug](https://github.com/SantoshDhaladhuli/celery-dag/issues/new?template=bug_report.md)
282
+ * [Request a Feature](https://github.com/SantoshDhaladhuli/celery-dag/issues/new?template=feature_request.md)
283
+ * [Submit a Pull Request](https://github.com/SantoshDhaladhuli/celery-dag/pulls)
284
+
285
+ ---
286
+
287
+ ## 👤 Author & Maintainer
288
+
289
+ Created and maintained by **Santosh Dhaladhuli**:
290
+ * **GitHub**: [@SantoshDhaladhuli](https://github.com/SantoshDhaladhuli)
291
+ * **Email**: [santoshsai666@gmail.com](mailto:santoshsai666@gmail.com)
292
+
293
+ ---
294
+
295
+ ## ⚖️ License
296
+
297
+ Distributed under the **Apache License 2.0**. See [`LICENSE`](LICENSE) for details.