Skip to content

Commit 9449070

Browse files
authored
feat(core): persist physical queue identity for flow tasks (#679)
## Summary Persist physical queue identity independently of flow identity while keeping today's one-flow/one-queue behavior (#650). Replacement for rejected #677. Stacked on the test-harness startup fix #680; each PR contains one commit. - Store canonical `queue_name` on steps and task snapshots; enforce partial `(queue_name, message_id)` uniqueness while retaining nullable message IDs and the task primary key. Lifecycle operations use stored routes, grouped by queue, with existing concurrency, terminal-state and visibility safeguards. - **Breaking claim API:** SQL `pgflow.start_tasks(flow_slug, msg_ids, worker_id, queue_name)` and TypeScript `startTasks()` require the canonical queue argument (`lower(flow_slug)` today). The released three-argument SQL overload is removed; no default, fallback or compatibility shim remains. JavaScript message IDs are exact decimal strings. - **No hot-path queue listing:** PGMQ already normalizes message-operation names. Remove `_effective_queue_name`, its session cache, and worker spelling-resolution plumbing. Pruning also uses canonical routes directly. Public listing remains for provisioning collisions and fresh original-spelling resolution before destructive queue deletion. Existing mixed-case queues remain usable without moving messages or recreating queues. - Preserve exact-flow ownership checks, ambiguous-match rejection before destructive work, transactional deletion, single-read claiming, and unmatched/wrong-flow message preservation. Keep accepted `set_vt_batch()` and direct archive pruning. - Regenerate the unreleased `20260913093141_pgflow_persist_queue_identity` migration: nullable adds, populated backfill, constraints, then new functions and removal of the old claim overload. Bounded lock waits and atomic rollback safeguards remain. Update the maintenance guide, pruning instructions, lifecycle diagram and 0.17.0 news article. ## Maintenance upgrade No mixed-version rolling upgrade. Pause producers; record worker enablement and running process states before changing them; drain active handlers under the old schema; stop workers and re-invocation; quiesce maintenance/recovery/definition writers; apply migrations to the explicit target through Supabase's runner; replace any installed pruning helper; deploy matching packages and callers; restore the saved states and resume producers. Draining active work does not mean emptying queues. Queued tasks and messages survive the upgrade. A failed migration rolls back; after success, old three-argument workers cannot simply restart. ## Checks Three GLM implementation / independent Sol review rounds completed. Final code and documentation review: **APPROVED**. - Full core pgTAP: **300 files / 1,464 tests pass**, including populated 0.16.0 upgrade and conflict rollback fixtures. - Edge-worker unit: **254 pass**; edge-worker E2E and portable-runtime E2E: **12 each pass**; client E2E: **47 pass**. - Migration/generated-type checks, website lint/build/link checks, changeset validation and post-commit affected prepush: **pass** (32/32 prepush tasks). - Current-head GitHub CI **passes edge-worker integration**, core pgTAP, build/test, edge-worker E2E, client/CLI E2E, smoke, type infrastructure and changesets. The local integration timeout did not recur in CI. - **Remaining CI blocker:** portable-runtime E2E is **11/12**. `portable runtimes - max_concurrency works in supabase` fails with `Timeout after 60000ms waiting for test_seq to increment by 200`. One targeted failed-job rerun reproduced the same failure. Local portable-runtime suites passed twice; that does not establish the cause of the CI failure. No timeout or assertion was weakened. Three authorized correction/review rounds are exhausted. Closes #650
2 parents e66a3d7 + 01147fe commit 9449070

113 files changed

Lines changed: 4629 additions & 380 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@pgflow/core': minor
3+
'@pgflow/dsl': minor
4+
'@pgflow/client': minor
5+
'@pgflow/edge-worker': minor
6+
'pgflow': minor
7+
---
8+
9+
Persist physical queue identity on steps and tasks. A queued task's message identity is now `(queue_name, message_id)`, not `message_id` alone, preparing pgflow for private per-step queues while keeping one-flow/one-queue behavior.
10+
11+
`pgflow.steps` and `pgflow.step_tasks` gain a canonical lowercase `queue_name` (snapshot at task creation), `(queue_name, message_id)` is unique per queue, and two flows can no longer share a normalized default queue. **Breaking:** `pgflow.start_tasks()` now requires the `queue_name` argument - the queue's canonical identity, `lower(flow_slug)` today - and the released three-argument form and the NULL default are gone, and `startTasks()` on `IPgflowClient`/`PgflowSqlClient` requires the queue argument as well. pgflow's own workers poll and claim through that canonical name; custom callers must pass it explicitly. There is no mixed-version rolling upgrade: stop and drain workers, pause producers and definition/maintenance/recovery writers, apply the transactional migration through Supabase's migration runner against the production database (`--linked` or `--db-url`, not the local default), replace the optional `prune_data_older_than()` helper, then deploy matching packages and workers together, restoring the exact worker `enabled` states recorded before the window (see the 0.17.0 upgrade guide). Message ids are exact decimal strings at the JavaScript boundary. Existing mixed-case queue names keep working through their original pgmq spelling - PGMQ's public message API normalizes names, so no message or queue migration is needed.

‎ARCHITECTURE_GUIDE.md‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ export default CompleteExample;
172172

173173
**Critical Cross-Cutting Concepts**:
174174

175-
1. **Two-Phase Polling** - Worker calls `read_with_poll()` then `start_tasks(workerId)` to prevent race conditions
175+
1. **Two-Phase Polling** - Worker calls `read_with_poll()` then `start_tasks(workerId, queue_name)` to prevent race conditions
176176
2. **Empty Array Cascade** - When `initial_tasks=0`, `cascade_complete_taskless_steps()` completes entire dependent chain in one transaction
177177
3. **Map Step `initial_tasks` Lifecycle**:
178178
- Root maps: Set at flow start from input array length
@@ -204,7 +204,7 @@ export default CompleteExample;
204204
2. Main loop:
205205
- `sendHeartbeat()` - Update status, check deprecation
206206
- If deprecated → exit gracefully
207-
- Two-phase polling: `readMessages()` then `startTasks(workerId)`
207+
- Two-phase polling: `readMessages()` then `startTasks(workerId, queueName)`
208208
- Execute handlers (up to `maxConcurrent` parallel)
209209
- `complete_task()` or `fail_task()`
210210
3. On shutdown:
@@ -228,8 +228,7 @@ const supabase = createClient(
228228

229229
// Create worker with all configuration options
230230
const worker = createFlowWorker(supabase, MyFlow, {
231-
// Queue configuration
232-
queueName: 'tasks', // Default: 'tasks'
231+
// The worker polls the flow's canonical queue: lower(flow_slug)
233232

234233
// Polling configuration
235234
maxPollSeconds: 2, // Default: 2
@@ -313,7 +312,7 @@ await worker.start();
313312

314313
**How**:
315314
- Phase 1: Worker calls `read_with_poll()` - reserves messages, returns `msg_id`s
316-
- Phase 2: Worker calls `start_tasks(flow_slug, msg_ids, workerId)` - creates `step_tasks`, returns details
315+
- Phase 2: Worker calls `start_tasks(flow_slug, msg_ids, worker_id, queue_name)` - creates `step_tasks`, returns details
317316

318317
**See**:
319318
- Worker implementation: `/pkgs/edge-worker/src/worker/FlowWorkerLifecycle.ts`

‎pkgs/client/__tests__/helpers/polling.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,10 @@ export async function readAndStart<TFlow extends AnyFlow>(
5353
return [];
5454
}
5555

56-
// 4. Start the tasks and return the resulting rows
56+
// 4. Start the tasks and return the resulting rows. The claim receives the
57+
// queue this helper read from (the canonical lowercase flow slug)
5758
const msgIds = messages.map(m => m.msg_id);
58-
const tasks = await sqlClient.startTasks(flowSlug, msgIds, workerId);
59+
const tasks = await sqlClient.startTasks(flowSlug, msgIds, workerId, flowSlug.toLowerCase());
5960

6061
return tasks;
6162
}

‎pkgs/core/README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,8 @@ SELECT * FROM pgmq.read_with_poll(
288288
SELECT * FROM pgflow.start_tasks(
289289
flow_slug => 'analyze_website',
290290
msg_ids => ARRAY[101, 102, 103], -- message IDs from phase 1
291-
worker_id => '550e8400-e29b-41d4-a716-446655440000'::uuid
291+
worker_id => '550e8400-e29b-41d4-a716-446655440000'::uuid,
292+
queue_name => 'analyze_website' -- the queue's canonical name: lower(flow_slug), the exact spelling tasks store (#650)
292293
);
293294
```
294295

‎pkgs/core/__tests__/types/PgflowSqlClient.test-d.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ describe('PgflowSqlClient Type Compatibility with Flow', () => {
2626
// Check startTasks method types
2727
expectTypeOf(client.startTasks).toBeFunction();
2828
expectTypeOf(client.startTasks).parameters.toMatchTypeOf<
29-
[string, number[], string]
29+
[string, string[], string, string]
3030
>();
3131
expectTypeOf(client.startTasks).returns.toEqualTypeOf<
3232
Promise<StepTaskRecord<typeof flow>[]>
@@ -66,19 +66,22 @@ describe('PgflowSqlClient Type Compatibility with Flow', () => {
6666
const client = new PgflowSqlClient<typeof flow>(sql);
6767

6868
// Valid calls should compile
69-
client.startTasks('flow_slug', [1, 2, 3], 'worker-id');
70-
client.startTasks('flow_slug', [], 'worker-id');
69+
client.startTasks('flow_slug', ['1', '2', '3'], 'worker-id', 'flow_slug');
70+
client.startTasks('flow_slug', [], 'worker-id', 'flow_slug');
71+
72+
// @ts-expect-error - queueName is required (#650): no default queue fallback
73+
client.startTasks('flow_slug', ['1'], 'worker-id');
7174

7275
// @ts-expect-error - flowSlug must be string
73-
client.startTasks(123, [1, 2, 3], 'worker-id');
76+
client.startTasks(123, ['1', '2', '3'], 'worker-id', 'flow_slug');
7477

75-
// @ts-expect-error - msgIds must be number array
76-
client.startTasks('flow_slug', ['1', '2', '3'], 'worker-id');
78+
// @ts-expect-error - msgIds must be string array (exact decimal strings, #650)
79+
client.startTasks('flow_slug', [1, 2, 3], 'worker-id', 'flow_slug');
7780

7881
// @ts-expect-error - msgIds must be array
79-
client.startTasks('flow_slug', 123, 'worker-id');
82+
client.startTasks('flow_slug', 123, 'worker-id', 'flow_slug');
8083

8184
// @ts-expect-error - workerId must be string
82-
client.startTasks('flow_slug', [1, 2, 3], 123);
85+
client.startTasks('flow_slug', ['1', '2', '3'], 123, 'flow_slug');
8386
});
8487
});

‎pkgs/core/assets/flow-lifecycle.mermaid‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ sequenceDiagram
2424
PGMQ-->>Worker: Return messages
2525
deactivate PGMQ
2626

27-
Worker->>pgflow: start_tasks(flow_slug, msg_ids, worker_id)
27+
Worker->>pgflow: start_tasks(flow_slug, msg_ids, worker_id, queue_name)
2828
activate pgflow
2929
pgflow->>pgflow: Find step_tasks with matching message_ids
3030
pgflow->>pgflow: Mark tasks as 'started' with worker_id

‎pkgs/core/assets/flow-lifecycle.svg‎

Lines changed: 1 addition & 1 deletion
Loading

‎pkgs/core/schemas/0030_utilities.sql‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,23 @@ begin
3535
end;
3636
$$;
3737

38+
create or replace function pgflow.is_valid_queue_name(
39+
queue_name text
40+
)
41+
returns boolean
42+
language sql
43+
immutable
44+
set search_path = ''
45+
as $$
46+
-- Mirrors pgmq.validate_queue_name() (47-character limit) and additionally
47+
-- requires the canonical lowercase spelling pgflow stores (#650).
48+
select
49+
queue_name is not null
50+
and queue_name <> ''
51+
and length(queue_name) <= 47
52+
and queue_name = lower(queue_name)
53+
$$;
54+
3855
create or replace function pgflow.calculate_retry_delay(
3956
base_delay numeric,
4057
attempts_count int
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
-- Resolve a stored canonical queue name to the spelling listed in pgmq.
2+
--
3+
-- pgflow stores canonical lowercase queue names (#650). A queue created by an
4+
-- older pgflow release may be listed under its original mixed-case spelling.
5+
-- PGMQ's public message operations (send_batch, read_with_poll, set_vt,
6+
-- archive, delete) normalize names themselves, so message paths address the
7+
-- queue by its stored canonical name directly and never resolve anything.
8+
--
9+
-- Only operations that must address the queue's physical objects by their
10+
-- original spelling need this helper today: delete_flow_and_data (drop_queue
11+
-- drops metadata and tables under the listed spelling). The helper resolves
12+
-- the listed spelling through pgmq.list_queues() and never creates a second
13+
-- metadata entry. An ambiguous case-insensitive match (external damage) is
14+
-- rejected before any destructive work; an unlisted name is passed through
15+
-- unchanged so PGMQ reports the operation's own error.
16+
17+
-- Fresh resolution against pgmq.list_queues().
18+
create or replace function pgflow._listed_queue_name(p_queue_name text)
19+
returns text
20+
language plpgsql
21+
stable
22+
set search_path = ''
23+
as $$
24+
declare
25+
v_matches text[];
26+
begin
27+
-- Resolve every listed spelling of the normalized name before preferring
28+
-- any single match: an ambiguous pair is rejected even when one spelling
29+
-- is the exact requested name (#650).
30+
select array_agg(listed.queue_name order by listed.queue_name)
31+
into v_matches
32+
from pgmq.list_queues() as listed
33+
where lower(listed.queue_name) = lower(p_queue_name);
34+
35+
if v_matches is null then
36+
-- Not listed: pass through; PGMQ reports its own error (or no-ops)
37+
return p_queue_name;
38+
elsif cardinality(v_matches) > 1 then
39+
raise exception
40+
'queue name "%" is ambiguous: it matches listed queues %',
41+
p_queue_name, v_matches
42+
using errcode = 'ambiguous_alias';
43+
else
44+
return v_matches[1];
45+
end if;
46+
end;
47+
$$;

‎pkgs/core/schemas/0050_tables_definitions.sql‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ create table pgflow.flows (
1717
create table pgflow.steps (
1818
flow_slug text not null references pgflow.flows(flow_slug),
1919
step_slug text not null,
20+
-- Canonical queue this step's tasks are dispatched to (#650).
21+
-- For this stage every step routes to the flow's default queue: lower(flow_slug).
22+
queue_name text not null,
2023
step_type text not null default 'single',
2124
step_index int not null default 0,
2225
deps_count int not null default 0 check (deps_count >= 0),
@@ -38,6 +41,7 @@ create table pgflow.steps (
3841
primary key (flow_slug, step_slug),
3942
unique (flow_slug, step_index), -- Ensure step_index is unique within a flow
4043
check (pgflow.is_valid_slug(step_slug)),
44+
constraint queue_name_is_valid check (pgflow.is_valid_queue_name(queue_name)),
4145
check (step_type in ('single', 'map')),
4246
constraint opt_max_attempts_is_nonnegative check (opt_max_attempts is null or opt_max_attempts >= 0),
4347
constraint opt_base_delay_is_nonnegative check (opt_base_delay is null or opt_base_delay >= 0),
@@ -63,3 +67,8 @@ create table pgflow.deps (
6367

6468
create index if not exists idx_deps_by_flow_step on pgflow.deps (flow_slug, step_slug);
6569
create index if not exists idx_deps_by_flow_dep on pgflow.deps (flow_slug, dep_slug);
70+
71+
-- Two concrete flows must not address the same normalized default queue (#650).
72+
-- The expression index also rejects direct SQL creation of conflicting flows.
73+
create unique index if not exists idx_flows_normalized_slug
74+
on pgflow.flows (lower(flow_slug));

0 commit comments

Comments
 (0)