@pgflow/core 0.0.0-0-10-0-ac3e1101-20251210151347

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 (33) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +492 -0
  3. package/dist/CHANGELOG.md +828 -0
  4. package/dist/PgflowSqlClient.d.ts +17 -0
  5. package/dist/PgflowSqlClient.d.ts.map +1 -0
  6. package/dist/PgflowSqlClient.js +70 -0
  7. package/dist/README.md +492 -0
  8. package/dist/database-types.d.ts +1108 -0
  9. package/dist/database-types.d.ts.map +1 -0
  10. package/dist/database-types.js +8 -0
  11. package/dist/index.d.ts +4 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +2 -0
  14. package/dist/package.json +31 -0
  15. package/dist/supabase/migrations/20250429164909_pgflow_initial.sql +579 -0
  16. package/dist/supabase/migrations/20250517072017_pgflow_fix_poll_for_tasks_to_use_separate_statement_for_polling.sql +101 -0
  17. package/dist/supabase/migrations/20250609105135_pgflow_add_start_tasks_and_started_status.sql +371 -0
  18. package/dist/supabase/migrations/20250610180554_pgflow_add_set_vt_batch_and_use_it_in_start_tasks.sql +127 -0
  19. package/dist/supabase/migrations/20250614124241_pgflow_add_realtime.sql +501 -0
  20. package/dist/supabase/migrations/20250619195327_pgflow_fix_fail_task_missing_realtime_event.sql +185 -0
  21. package/dist/supabase/migrations/20250627090700_pgflow_fix_function_search_paths.sql +6 -0
  22. package/dist/supabase/migrations/20250707210212_pgflow_add_opt_start_delay.sql +103 -0
  23. package/dist/supabase/migrations/20250719205006_pgflow_worker_deprecation.sql +2 -0
  24. package/dist/supabase/migrations/20251006073122_pgflow_add_map_step_type.sql +1244 -0
  25. package/dist/supabase/migrations/20251103222045_pgflow_fix_broadcast_order_and_timestamp_handling.sql +622 -0
  26. package/dist/supabase/migrations/20251104080523_pgflow_upgrade_pgmq_1_5_1.sql +93 -0
  27. package/dist/supabase/migrations/20251130000000_pgflow_auto_compilation.sql +268 -0
  28. package/dist/supabase/migrations/20251209074533_pgflow_worker_management.sql +273 -0
  29. package/dist/tsconfig.lib.tsbuildinfo +1 -0
  30. package/dist/types.d.ts +93 -0
  31. package/dist/types.d.ts.map +1 -0
  32. package/dist/types.js +1 -0
  33. package/package.json +31 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 Wojciech Majewski <owner@pgflow.dev>
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,492 @@
1
+ # pgflow SQL Core
2
+
3
+ PostgreSQL-native workflow engine for defining, managing, and tracking DAG-based workflows directly in your database.
4
+
5
+ > [!NOTE]
6
+ > This project and all its components are licensed under [Apache 2.0](./LICENSE) license.
7
+
8
+ ## Table of Contents
9
+
10
+ - [Overview](#overview)
11
+ - [Key Features](#key-features)
12
+ - [Architecture](#architecture)
13
+ - [Schema Design](#schema-design)
14
+ - [Execution Model](#execution-model)
15
+ - [Example Flow and its life](#example-flow-and-its-life)
16
+ - [Defining a Workflow](#defining-a-workflow)
17
+ - [Starting a Workflow Run](#starting-a-workflow-run)
18
+ - [Workflow Execution](#workflow-execution)
19
+ - [Task Polling](#task-polling)
20
+ - [Task Completion](#task-completion)
21
+ - [Error Handling](#error-handling)
22
+ - [Retries and Timeouts](#retries-and-timeouts)
23
+ - [TypeScript Flow DSL](#typescript-flow-dsl)
24
+ - [Overview](#overview-1)
25
+ - [Type Inference System](#type-inference-system)
26
+ - [Basic Example](#basic-example)
27
+ - [How Payload Types Are Built](#how-payload-types-are-built)
28
+ - [Benefits of Automatic Type Inference](#benefits-of-automatic-type-inference)
29
+ - [Data Flow](#data-flow)
30
+ - [Input and Output Handling](#input-and-output-handling)
31
+ - [Run Completion](#run-completion)
32
+
33
+ ## Overview
34
+
35
+ The pgflow SQL Core provides the data model, state machine, and transactional functions for workflow management. It treats workflows as Directed Acyclic Graphs (DAGs) of steps, each step being a simple state machine.
36
+
37
+ This package focuses on:
38
+
39
+ - Defining and storing workflow shapes
40
+ - Managing workflow state transitions
41
+ - Exposing transactional functions for workflow operations
42
+ - Providing two-phase APIs for reliable task polling and status updates
43
+
44
+ The actual execution of workflow tasks is handled by the [Edge Worker](../edge-worker/README.md), which calls back to the SQL Core to acknowledge task completion or failure.
45
+
46
+ ## Requirements
47
+
48
+ > [!IMPORTANT] > **pgmq Version Requirement** (since v0.8.0)
49
+ >
50
+ > pgflow v0.8.0 and later requires **pgmq 1.5.0 or higher**. This version of pgflow will NOT work with pgmq 1.4.x or earlier.
51
+ >
52
+ > - **Supabase Cloud**: Recent versions include pgmq 1.5.0+ by default
53
+ > - **Self-hosted**: You must upgrade pgmq to version 1.5.0+ before upgrading pgflow
54
+ > - **Version Check**: Run `SELECT extversion FROM pg_extension WHERE extname = 'pgmq';` to verify your pgmq version
55
+
56
+ ## Key Features
57
+
58
+ - **Declarative Workflows**: Define flows and steps via SQL tables
59
+ - **Dependency Management**: Explicit step dependencies with atomic transitions
60
+ - **Configurable Behavior**: Per-flow and per-step options for timeouts, retries, and delays
61
+ - **Queue Integration**: Built on pgmq for reliable task processing
62
+ - **Transactional Guarantees**: All state transitions are ACID-compliant
63
+
64
+ ## Architecture
65
+
66
+ ### Schema Design
67
+
68
+ [Schema ERD Diagram (click to enlarge)](./assets/schema.svg)
69
+
70
+ <a href="./assets/schema.svg">
71
+ <img src="./assets/schema.svg" alt="Schema ERD Diagram" width="25%" height="25%">
72
+ </a>
73
+
74
+ ---
75
+
76
+ The schema consists of two main categories of tables:
77
+
78
+ #### Static definition tables
79
+
80
+ - `flows` (just an identity for the workflow with some global options)
81
+ - `steps` (DAG nodes belonging to particular `flows`, with option overrides)
82
+ - `deps` (DAG edges between `steps`)
83
+
84
+ #### Runtime state tables
85
+
86
+ - `runs` (execution instances of `flows`)
87
+ - `step_states` (states of individual `steps` within a `run`)
88
+ - `step_tasks` (units of work for individual `steps` within a `run`, so we can have fanouts)
89
+
90
+ ### Execution Model
91
+
92
+ The SQL Core handles the workflow lifecycle through these key operations:
93
+
94
+ 1. **Definition**: Workflows are defined using `create_flow` and `add_step`
95
+ 2. **Instantiation**: Workflow instances are started with `start_flow`, creating a new run
96
+ 3. **Task Retrieval**: The [Edge Worker](../edge-worker/README.md) uses two-phase polling - first `read_with_poll` to reserve queue messages, then `start_tasks` to convert them to executable tasks
97
+ 4. **State Transitions**: When the Edge Worker reports back using `complete_task` or `fail_task`, the SQL Core handles state transitions and schedules dependent steps
98
+
99
+ [Flow lifecycle diagram (click to enlarge)](./assets/flow-lifecycle.svg)
100
+
101
+ <a href="./assets/flow-lifecycle.svg"><img src="./assets/flow-lifecycle.svg" alt="Flow Lifecycle" width="25%" height="25%"></a>
102
+
103
+ ## Step Types
104
+
105
+ pgflow supports two fundamental step types that control how tasks are created and executed:
106
+
107
+ ### Single Steps (Default)
108
+
109
+ Single steps are the standard step type where each step creates exactly one task when started. These steps process their input as a whole and return a single output value.
110
+
111
+ ```sql
112
+ -- Regular single step definition
113
+ SELECT pgflow.add_step('my_flow', 'process_data');
114
+ ```
115
+
116
+ ### Map Steps
117
+
118
+ Map steps enable parallel processing of arrays by automatically creating multiple tasks - one for each array element. The system handles task distribution, parallel execution, and output aggregation transparently.
119
+
120
+ ```sql
121
+ -- Map step definition (step_type => 'map')
122
+ SELECT pgflow.add_step(
123
+ flow_slug => 'my_flow',
124
+ step_slug => 'process_items',
125
+ deps_slugs => ARRAY['fetch_items'],
126
+ step_type => 'map'
127
+ );
128
+ ```
129
+
130
+ #### Key Characteristics
131
+
132
+ - **Multiple Task Creation**: The SQL core creates N tasks for a map step (one per array element), unlike single steps which create one task
133
+ - **Element Distribution**: The SQL core distributes individual array elements to tasks based on `task_index`
134
+ - **Output Aggregation**: The SQL core aggregates task outputs back into an array for dependent steps
135
+ - **Constraint**: Map steps can have at most one dependency (which must return an array), or zero dependencies (then flow input must be an array)
136
+
137
+ #### Map Step Execution Flow
138
+
139
+ 1. **Array Input Validation**: The SQL core validates that the input is an array
140
+ 2. **Task Creation**: The SQL core creates N tasks with indices 0 to N-1
141
+ 3. **Element Distribution**: The SQL core assigns `array[task_index]` as input to each task
142
+ 4. **Parallel Execution**: Edge workers execute tasks independently in parallel
143
+ 5. **Output Collection**: The SQL core aggregates outputs preserving array order
144
+ 6. **Dependent Activation**: The SQL core passes the aggregated array to dependent steps
145
+
146
+ #### Root Map vs Dependent Map
147
+
148
+ **Root Map Steps** process the flow's input array directly:
149
+
150
+ ```sql
151
+ -- Root map: no dependencies, processes flow input
152
+ SELECT pgflow.add_step(
153
+ flow_slug => 'batch_processor',
154
+ step_slug => 'process_each',
155
+ step_type => 'map'
156
+ );
157
+
158
+ -- Starting the flow with array input
159
+ SELECT pgflow.start_flow(
160
+ flow_slug => 'batch_processor',
161
+ input => '[1, 2, 3, 4, 5]'::jsonb
162
+ );
163
+ ```
164
+
165
+ **Dependent Map Steps** process another step's array output:
166
+
167
+ ```sql
168
+ -- Dependent map: processes the array from 'fetch_items'
169
+ SELECT pgflow.add_step(
170
+ flow_slug => 'data_pipeline',
171
+ step_slug => 'transform_each',
172
+ deps_slugs => ARRAY['fetch_items'],
173
+ step_type => 'map'
174
+ );
175
+ ```
176
+
177
+ #### Edge Cases and Special Behaviors
178
+
179
+ 1. **Empty Array Cascade**: When a map step receives an empty array (`[]`):
180
+
181
+ - The SQL core completes it immediately without creating tasks
182
+ - The completed map step outputs an empty array
183
+ - Any dependent map steps also receive empty arrays and complete immediately
184
+ - This cascades through the entire chain of map steps in a single transaction
185
+ - Example: `[] → map1 → [] → map2 → [] → map3 → []` all complete together
186
+
187
+ 2. **NULL Values**: NULL array elements are preserved and distributed to their respective tasks
188
+
189
+ 3. **Non-Array Input**: The SQL core fails the step when input is not an array
190
+
191
+ 4. **Type Violations**: When a single step outputs non-array data to a map step, the SQL core fails the entire run (stores the invalid output for debugging, archives all queued messages, prevents orphaned tasks)
192
+
193
+ #### Implementation Details
194
+
195
+ Map steps utilize several database fields for state management:
196
+
197
+ - `initial_tasks`: Number of tasks to create (NULL until array size is known)
198
+ - `remaining_tasks`: Tracks incomplete tasks for the step
199
+ - `task_index`: Identifies which array element each task processes
200
+ - `step_type`: Column value 'map' triggers map behavior
201
+
202
+ The aggregation process ensures:
203
+
204
+ - **Order Preservation**: Task outputs maintain array element ordering
205
+ - **NULL Handling**: NULL outputs are included in the aggregated array
206
+ - **Atomicity**: Aggregation occurs within the same transaction as task completion
207
+
208
+ ## Example flow and its life
209
+
210
+ Let's walk through creating and running a workflow that fetches a website,
211
+ does summarization and sentiment analysis in parallel steps
212
+ and saves the results to a database.
213
+
214
+ ![example flow graph](./assets/example-flow.svg)
215
+
216
+ ### Defining a Workflow
217
+
218
+ Workflows are defined using two SQL functions: `create_flow` and `add_step`.
219
+
220
+ In this example, we'll create a workflow with:
221
+
222
+ - `website` as the entry point ("root step")
223
+ - `sentiment` and `summary` as parallel steps that depend on `website`
224
+ - `saveToDb` as the final step, depending on both parallel steps
225
+
226
+ ```sql
227
+ -- Define workflow with parallel steps
228
+ SELECT pgflow.create_flow('analyze_website');
229
+ SELECT pgflow.add_step('analyze_website', 'website');
230
+ SELECT pgflow.add_step('analyze_website', 'sentiment', deps_slugs => ARRAY['website']);
231
+ SELECT pgflow.add_step('analyze_website', 'summary', deps_slugs => ARRAY['website']);
232
+ SELECT pgflow.add_step('analyze_website', 'saveToDb', deps_slugs => ARRAY['sentiment', 'summary']);
233
+ ```
234
+
235
+ > [!WARNING]
236
+ > You need to call `add_step` in topological order, which is enforced by foreign key constraints.
237
+
238
+ > [!NOTE]
239
+ > You can have multiple "root steps" in a workflow. You can even create a root-steps-only workflow
240
+ > to process a single input in parallel, because at the end, all of the outputs from steps
241
+ > that does not have dependents ("final steps") are aggregated and saved as run's `output`.
242
+
243
+ ### Starting a Workflow Run
244
+
245
+ To start a workflow, call `start_flow` with a flow slug and input arguments:
246
+
247
+ ```sql
248
+ SELECT * FROM pgflow.start_flow(
249
+ flow_slug => 'analyze_website',
250
+ input => '{"url": "https://example.com"}'::jsonb
251
+ );
252
+
253
+ -- run_id | flow_slug | status | input | output | remaining_steps
254
+ -- ------------+-----------------+---------+--------------------------------+--------+-----------------
255
+ -- <run uuid> | analyze_website | started | {"url": "https://example.com"} | [NULL] | 4
256
+ ```
257
+
258
+ When a workflow starts:
259
+
260
+ - A new `run` record is created
261
+ - Initial states for all steps are created
262
+ - Root steps are marked as `started`
263
+ - Tasks are created for root steps
264
+ - Messages are enqueued on PGMQ for worker processing
265
+
266
+ > [!NOTE]
267
+ > The `input` argument must be a valid JSONB object: string, number, boolean, array, object or null.
268
+
269
+ ### Workflow Execution
270
+
271
+ #### Task Polling
272
+
273
+ The Edge Worker uses a two-phase approach to retrieve and start tasks:
274
+
275
+ **Phase 1 - Reserve Messages:**
276
+
277
+ ```sql
278
+ SELECT * FROM pgmq.read_with_poll(
279
+ queue_name => 'analyze_website',
280
+ vt => 60, -- visibility timeout in seconds
281
+ qty => 5 -- maximum number of messages to fetch
282
+ );
283
+ ```
284
+
285
+ **Phase 2 - Start Tasks:**
286
+
287
+ ```sql
288
+ SELECT * FROM pgflow.start_tasks(
289
+ flow_slug => 'analyze_website',
290
+ msg_ids => ARRAY[101, 102, 103], -- message IDs from phase 1
291
+ worker_id => '550e8400-e29b-41d4-a716-446655440000'::uuid
292
+ );
293
+ ```
294
+
295
+ **How it works:**
296
+
297
+ 1. **read_with_poll** reserves raw queue messages and hides them from other workers
298
+ 2. **start_tasks** finds matching step_tasks, increments attempts counter, and builds task inputs
299
+ 3. Task metadata and input are returned to the worker for execution
300
+
301
+ This two-phase approach ensures tasks always exist before processing begins, eliminating race conditions that could occur with single-phase polling.
302
+
303
+ #### Task Completion
304
+
305
+ After successful processing, the worker acknowledges completion:
306
+
307
+ ```sql
308
+ SELECT pgflow.complete_task(
309
+ run_id => '<run_uuid>',
310
+ step_slug => 'website',
311
+ task_index => 0, -- we will have multiple tasks for a step in the future
312
+ output => '{"content": "HTML content", "status": 200}'::jsonb
313
+ );
314
+ ```
315
+
316
+ When a task completes:
317
+
318
+ 1. The task status is updated to 'completed' and the output is saved
319
+ 2. The message is archived in PGMQ
320
+ 3. The step state is updated to 'completed'
321
+ 4. Dependent steps with all dependencies completed are automatically started
322
+ 5. The run's remaining_steps counter is decremented
323
+ 6. If all steps are completed, the run is marked as completed with aggregated outputs
324
+
325
+ #### Error Handling
326
+
327
+ If a task fails, the worker acknowledges this using `fail_task`:
328
+
329
+ ```sql
330
+ SELECT pgflow.fail_task(
331
+ run_id => '<run_uuid>',
332
+ step_slug => 'website',
333
+ task_index => 0,
334
+ error_message => 'Connection timeout when fetching URL'::text
335
+ );
336
+ ```
337
+
338
+ The system handles failures by:
339
+
340
+ 1. Checking if retry attempts are available
341
+ 2. For available retries:
342
+ - Keeping the task in 'queued' status
343
+ - Applying exponential backoff for visibility
344
+ - Preventing processing until the visibility timeout expires
345
+ 3. When retries are exhausted:
346
+ - Marking the task as 'failed'
347
+ - Storing the task output (even for failed tasks)
348
+ - Marking the step as 'failed'
349
+ - Marking the run as 'failed'
350
+ - Archiving the message in PGMQ
351
+ - **Archiving all queued messages for the failed run** (preventing orphaned messages)
352
+ 4. Additional failure handling:
353
+ - **No retries on already-failed runs** - tasks are immediately marked as failed
354
+ - **Graceful type constraint violations** - handled without exceptions when single steps feed map steps
355
+ - **Stores invalid output on type violations** - captures the output that caused the violation for debugging
356
+ - **Performance-optimized message archiving** using indexed queries
357
+
358
+ #### Retries and Timeouts
359
+
360
+ Retry behavior can be configured at both the flow and step level:
361
+
362
+ ```sql
363
+ -- Flow-level defaults
364
+ SELECT pgflow.create_flow(
365
+ flow_slug => 'analyze_website',
366
+ max_attempts => 3, -- Maximum retry attempts (including first attempt)
367
+ base_delay => 5, -- Base delay in seconds for exponential backoff
368
+ timeout => 60 -- Task timeout in seconds
369
+ );
370
+
371
+ -- Step-level overrides
372
+ SELECT pgflow.add_step(
373
+ flow_slug => 'analyze_website',
374
+ step_slug => 'sentiment',
375
+ deps_slugs => ARRAY['website']::text[],
376
+ max_attempts => 5, -- Override max attempts for this step
377
+ base_delay => 2, -- Override base delay for exponential backoff
378
+ timeout => 30 -- Override timeout for this step
379
+ );
380
+ ```
381
+
382
+ The system applies exponential backoff for retries using the formula:
383
+
384
+ ```
385
+ delay = base_delay * (2 ^ attempts_count)
386
+ ```
387
+
388
+ Timeouts are enforced by setting the message visibility timeout to the step's timeout value plus a small buffer. If a worker doesn't acknowledge completion or failure within this period, the task becomes visible again and can be retried.
389
+
390
+ ## Workflow Definition with TypeScript DSL
391
+
392
+ The SQL Core is the DAG orchestration engine that handles dependency resolution, step state management, and task spawning. However, workflows are defined using the TypeScript Flow DSL, which compiles user intent into the SQL primitives that populate the definition tables (`flows`, `steps`, `deps`).
393
+
394
+ See the [@pgflow/dsl package](../dsl/README.md) for complete documentation on:
395
+
396
+ - Expressing workflows with type-safe method chaining
397
+ - Step types (`.step()`, `.array()`, `.map()`)
398
+ - Compilation to SQL migrations
399
+ - Type inference and handler context
400
+
401
+ The SQL Core executes these compiled definitions, managing when steps are ready, how many tasks to create (1 for single steps, N for map steps), and how to aggregate results.
402
+
403
+ ## Data Flow
404
+
405
+ ### Input and Output Handling
406
+
407
+ Handlers in pgflow **must return** JSON-serializable values that are captured and saved when `complete_task` is called. These outputs become available as inputs to dependent steps, allowing data to flow through your workflow pipeline.
408
+
409
+ When a step is executed, it receives an input object where:
410
+
411
+ - Each key is a step_slug of a completed dependency
412
+ - Each value is that step's output
413
+ - A special "run" key contains the original workflow input
414
+
415
+ #### Example: `sentiment`
416
+
417
+ When the `sentiment` step runs, it receives:
418
+
419
+ ```json
420
+ {
421
+ "run": { "url": "https://example.com" },
422
+ "website": { "content": "HTML content", "status": 200 }
423
+ }
424
+ ```
425
+
426
+ #### Example: `saveToDb`
427
+
428
+ The `saveToDb` step depends on both `sentiment` and `summary`:
429
+
430
+ ```json
431
+ {
432
+ "run": { "url": "https://example.com" },
433
+ "sentiment": { "score": 0.85, "label": "positive" },
434
+ "summary": "This website discusses various topics related to technology and innovation."
435
+ }
436
+ ```
437
+
438
+ ### Map Step Handler Inputs
439
+
440
+ Map step tasks receive a fundamentally different input structure than single step tasks. Instead of receiving an object with `run` and dependency keys, **map tasks receive only their assigned array element**:
441
+
442
+ #### Example: Processing user IDs
443
+
444
+ ```json
445
+ // Flow input (for root map) or dependency output:
446
+ ["user123", "user456", "user789"]
447
+
448
+ // What each map task receives:
449
+ // Task 0: "user123"
450
+ // Task 1: "user456"
451
+ // Task 2: "user789"
452
+
453
+ // NOT this:
454
+ // { "run": {...}, "dependency": [...] }
455
+ ```
456
+
457
+ This means:
458
+
459
+ - Map handlers process individual elements in isolation
460
+ - Map handlers cannot access the original flow input (`run`)
461
+ - Map handlers cannot access other dependencies
462
+ - Map handlers focus solely on transforming their assigned element
463
+
464
+ #### Map Step Outputs Become Arrays
465
+
466
+ When a step depends on a map step, it receives the aggregated array output:
467
+
468
+ ```json
469
+ // If 'process_users' is a map step that processed ["user1", "user2"]
470
+ // and output [{"name": "Alice"}, {"name": "Bob"}]
471
+
472
+ // A step depending on 'process_users' receives:
473
+ {
474
+ "run": {
475
+ /* original flow input */
476
+ },
477
+ "process_users": [{ "name": "Alice" }, { "name": "Bob" }] // Full array
478
+ }
479
+ ```
480
+
481
+ ### Run Completion
482
+
483
+ When all steps in a run are completed, the run status is automatically updated to 'completed' and its output is set. The output is an aggregation of all the outputs from final steps (steps that have no dependents):
484
+
485
+ ```sql
486
+ -- Example of a completed run with output
487
+ SELECT run_id, status, output FROM pgflow.runs WHERE run_id = '<run_uuid>';
488
+
489
+ -- run_id | status | output
490
+ -- ------------+-----------+-----------------------------------------------------
491
+ -- <run uuid> | completed | {"saveToDb": {"status": "success"}}
492
+ ```