From 3e9b5187ab7c3b34753d235dadb44acaebe9c686 Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Mon, 5 Oct 2026 20:11:21 +0000 Subject: [PATCH 01/10] Record `completed_at` for `ContinuedAsNew` executions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 8 + .../0027_continue_as_new_completed_at.sql | 341 ++++++++++++++++++ migrations/0027_diff.md | 318 ++++++++++++++++ migrations/README.md | 22 +- src/migrations.rs | 1 + tests/regression_tests.rs | 301 ++++++++++++++++ 6 files changed, 990 insertions(+), 1 deletion(-) create mode 100644 migrations/0027_continue_as_new_completed_at.sql create mode 100644 migrations/0027_diff.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 917c21b..ec0c1a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- Record `completed_at` for `ContinuedAsNew` executions so age-based execution + pruning also works for long-running workflows. Migration `0027` recovers + missing timestamps from terminal history events without changing current + execution protection. Rows without a recoverable terminal event remain NULL + and produce a migration warning. + ## [0.1.38] - 2026-10-26 ### Fixed diff --git a/migrations/0027_continue_as_new_completed_at.sql b/migrations/0027_continue_as_new_completed_at.sql new file mode 100644 index 0000000..6af41ca --- /dev/null +++ b/migrations/0027_continue_as_new_completed_at.sql @@ -0,0 +1,341 @@ +-- Copyright (c) Microsoft Corporation. +-- Licensed under the MIT License. + +-- Migration 0027: Record completion times for continued executions. +-- The acknowledgement body is unchanged from 0026 except for completion timestamps. + +DO $$ +DECLARE + v_schema_name TEXT := current_schema(); + v_unresolved BIGINT; +BEGIN + EXECUTE format($fmt$ + CREATE OR REPLACE FUNCTION %1$I.ack_orchestration_item( + p_lock_token TEXT, + p_now_ms BIGINT, + p_execution_id BIGINT, + p_history_delta JSONB, + p_worker_items JSONB, + p_orchestrator_items JSONB, + p_metadata JSONB, + p_cancelled_activities JSONB DEFAULT '[]'::JSONB + ) + RETURNS VOID AS $ack_orch$ + DECLARE + v_instance_id TEXT; + v_orchestration_name TEXT; + v_orchestration_version TEXT; + v_parent_instance_id TEXT; + v_status TEXT; + v_output TEXT; + v_completed_at TIMESTAMPTZ; + v_elem JSONB; + v_visible_at TIMESTAMPTZ; + v_fire_at_ms BIGINT; + v_item_instance_id TEXT; + v_item_execution_id BIGINT; + v_item_activity_id BIGINT; + v_item_session_id TEXT; + v_item_tag TEXT; + v_now_ts TIMESTAMPTZ; + v_custom_status_action TEXT; + v_custom_status_value TEXT; + v_current_execution_id BIGINT; + v_kv_mutations JSONB; + v_kv_item JSONB; + v_kv_action TEXT; + v_i INTEGER; + v_is_terminal BOOLEAN; + v_rows_affected INTEGER; + BEGIN + -- Convert Rust-supplied millisecond timestamp to TIMESTAMPTZ + v_now_ts := TO_TIMESTAMP(p_now_ms / 1000.0); + + -- Step 1: Validate lock token + SELECT il.instance_id INTO v_instance_id + FROM %1$I.instance_locks il + WHERE il.lock_token = p_lock_token AND il.locked_until > p_now_ms; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + + -- Step 1b: Take the advisory lock that fetch_orchestration_item takes + -- before it can take an instance over. Step 1 holds no lock, so a + -- fetch that judged the lease expired could otherwise replace the + -- token while this acknowledge runs. This acknowledge would then + -- commit its history and new work while its deletes below match no + -- rows, and the messages it processed would be delivered again. + PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); + + -- Step 1c: Revalidate the token after the wait. While this lock is + -- held, no fetch can replace it. + PERFORM 1 + FROM %1$I.instance_locks il + WHERE il.instance_id = v_instance_id + AND il.lock_token = p_lock_token; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + + -- Step 2: Extract metadata from JSONB + v_orchestration_name := p_metadata->>'orchestration_name'; + v_orchestration_version := p_metadata->>'orchestration_version'; + v_parent_instance_id := p_metadata->>'parent_instance_id'; + v_status := p_metadata->>'status'; + v_output := p_metadata->>'output'; + v_current_execution_id := p_execution_id; + v_is_terminal := v_status IN ('Completed', 'ContinuedAsNew', 'Failed'); + + -- Step 3: Create or update instance metadata (with explicit timestamps) + IF v_orchestration_name IS NOT NULL AND v_orchestration_version IS NOT NULL THEN + INSERT INTO %1$I.instances (instance_id, orchestration_name, orchestration_version, current_execution_id, parent_instance_id, created_at, updated_at) + VALUES (v_instance_id, v_orchestration_name, v_orchestration_version, p_execution_id, v_parent_instance_id, v_now_ts, v_now_ts) + ON CONFLICT (instance_id) DO NOTHING; + + UPDATE %1$I.instances i + SET orchestration_name = v_orchestration_name, + orchestration_version = v_orchestration_version, + parent_instance_id = COALESCE(i.parent_instance_id, v_parent_instance_id), + updated_at = v_now_ts + WHERE i.instance_id = v_instance_id; + END IF; + + -- Step 4: Create execution record (idempotent) + INSERT INTO %1$I.executions (instance_id, execution_id, status, started_at) + VALUES (v_instance_id, p_execution_id, 'Running', v_now_ts) + ON CONFLICT (instance_id, execution_id) DO NOTHING; + + -- Step 5: Update instance current_execution_id + UPDATE %1$I.instances i + SET current_execution_id = GREATEST(i.current_execution_id, p_execution_id), + updated_at = v_now_ts + WHERE i.instance_id = v_instance_id; + + -- Step 6: Append history_delta (batch insert with explicit timestamps) + IF p_history_delta IS NOT NULL AND JSONB_ARRAY_LENGTH(p_history_delta) > 0 THEN + INSERT INTO %1$I.history (instance_id, execution_id, event_id, event_type, event_data, created_at) + SELECT + v_instance_id, + p_execution_id, + (elem->>'event_id')::BIGINT, + elem->>'event_type', + elem->>'event_data', + v_now_ts + FROM JSONB_ARRAY_ELEMENTS(p_history_delta) AS elem; + END IF; + + -- Step 7: Update execution status if provided + IF v_status IS NOT NULL THEN + v_completed_at := CASE + WHEN v_is_terminal THEN v_now_ts + ELSE NULL + END; + + UPDATE %1$I.executions e + SET status = v_status, output = v_output, completed_at = v_completed_at + WHERE e.instance_id = v_instance_id AND e.execution_id = p_execution_id; + END IF; + + -- Step 7b: Store pinned duroxide version if provided in metadata + IF p_metadata ? 'pinned_duroxide_version' AND p_metadata->'pinned_duroxide_version' IS NOT NULL + AND p_metadata->>'pinned_duroxide_version' != 'null' THEN + UPDATE %1$I.executions + SET duroxide_version_major = (p_metadata->'pinned_duroxide_version'->>'major')::INTEGER, + duroxide_version_minor = (p_metadata->'pinned_duroxide_version'->>'minor')::INTEGER, + duroxide_version_patch = (p_metadata->'pinned_duroxide_version'->>'patch')::INTEGER + WHERE instance_id = v_instance_id AND execution_id = p_execution_id; + END IF; + + -- Step 7c: Handle custom_status update on instances table + v_custom_status_action := p_metadata->>'custom_status_action'; + IF v_custom_status_action = 'set' THEN + v_custom_status_value := p_metadata->>'custom_status_value'; + UPDATE %1$I.instances + SET custom_status = v_custom_status_value, + custom_status_version = custom_status_version + 1 + WHERE instance_id = v_instance_id; + ELSIF v_custom_status_action = 'clear' THEN + UPDATE %1$I.instances + SET custom_status = NULL, + custom_status_version = custom_status_version + 1 + WHERE instance_id = v_instance_id; + END IF; + + -- Step 7d: Materialize KV mutations into kv_delta only + v_kv_mutations := p_metadata->'kv_mutations'; + IF v_kv_mutations IS NOT NULL AND jsonb_array_length(v_kv_mutations) > 0 THEN + FOR v_i IN 0..jsonb_array_length(v_kv_mutations) - 1 LOOP + v_kv_item := v_kv_mutations->v_i; + v_kv_action := v_kv_item->>'action'; + IF v_kv_action = 'set' THEN + INSERT INTO %1$I.kv_delta (instance_id, key, value, last_updated_at_ms) + VALUES (v_instance_id, v_kv_item->>'key', v_kv_item->>'value', COALESCE((v_kv_item->>'last_updated_at_ms')::BIGINT, p_now_ms)) + ON CONFLICT (instance_id, key) + DO UPDATE SET value = EXCLUDED.value, last_updated_at_ms = EXCLUDED.last_updated_at_ms; + ELSIF v_kv_action = 'clear_key' THEN + INSERT INTO %1$I.kv_delta (instance_id, key, value, last_updated_at_ms) + VALUES (v_instance_id, v_kv_item->>'key', NULL, p_now_ms) + ON CONFLICT (instance_id, key) + DO UPDATE SET value = NULL, last_updated_at_ms = EXCLUDED.last_updated_at_ms; + ELSIF v_kv_action = 'clear_all' THEN + UPDATE %1$I.kv_delta + SET value = NULL, + last_updated_at_ms = p_now_ms + WHERE instance_id = v_instance_id; + + INSERT INTO %1$I.kv_delta (instance_id, key, value, last_updated_at_ms) + SELECT ks.instance_id, ks.key, NULL, p_now_ms + FROM %1$I.kv_store ks + WHERE ks.instance_id = v_instance_id + ON CONFLICT (instance_id, key) DO NOTHING; + END IF; + END LOOP; + END IF; + + -- Step 7e: Merge kv_delta into kv_store on terminal execution boundaries + IF v_is_terminal THEN + INSERT INTO %1$I.kv_store (instance_id, key, value, execution_id, last_updated_at_ms) + SELECT kd.instance_id, kd.key, kd.value, p_execution_id, kd.last_updated_at_ms + FROM %1$I.kv_delta kd + WHERE kd.instance_id = v_instance_id AND kd.value IS NOT NULL + ON CONFLICT (instance_id, key) + DO UPDATE SET value = EXCLUDED.value, + execution_id = EXCLUDED.execution_id, + last_updated_at_ms = EXCLUDED.last_updated_at_ms; + + DELETE FROM %1$I.kv_store ks + WHERE ks.instance_id = v_instance_id + AND ks.key IN ( + SELECT kd.key + FROM %1$I.kv_delta kd + WHERE kd.instance_id = v_instance_id + AND kd.value IS NULL + ); + + DELETE FROM %1$I.kv_delta kd + WHERE kd.instance_id = v_instance_id; + END IF; + + -- Step 8: Enqueue worker items with session_id and tag support + IF p_worker_items IS NOT NULL AND JSONB_ARRAY_LENGTH(p_worker_items) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_worker_items) LOOP + IF v_elem ? 'ActivityExecute' THEN + v_item_instance_id := v_elem->'ActivityExecute'->>'instance'; + v_item_execution_id := (v_elem->'ActivityExecute'->>'execution_id')::BIGINT; + v_item_activity_id := (v_elem->'ActivityExecute'->>'id')::BIGINT; + v_item_session_id := v_elem->'ActivityExecute'->>'session_id'; + v_item_tag := v_elem->'ActivityExecute'->>'tag'; + ELSE + v_item_instance_id := NULL; + v_item_execution_id := NULL; + v_item_activity_id := NULL; + v_item_session_id := NULL; + v_item_tag := NULL; + END IF; + + INSERT INTO %1$I.worker_queue (work_item, visible_at, created_at, instance_id, execution_id, activity_id, session_id, tag) + VALUES (v_elem::TEXT, v_now_ts, v_now_ts, v_item_instance_id, v_item_execution_id, v_item_activity_id, v_item_session_id, v_item_tag); + END LOOP; + END IF; + + -- Step 9: Delete cancelled activities from worker_queue (lock stealing) + IF p_cancelled_activities IS NOT NULL AND JSONB_ARRAY_LENGTH(p_cancelled_activities) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_cancelled_activities) LOOP + DELETE FROM %1$I.worker_queue + WHERE instance_id = v_elem->>'instance' + AND execution_id = (v_elem->>'execution_id')::BIGINT + AND activity_id = (v_elem->>'activity_id')::BIGINT; + END LOOP; + END IF; + + -- Step 10: Enqueue orchestrator items + IF p_orchestrator_items IS NOT NULL AND JSONB_ARRAY_LENGTH(p_orchestrator_items) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_orchestrator_items) LOOP + IF v_elem ? 'StartOrchestration' THEN + v_item_instance_id := v_elem->'StartOrchestration'->>'instance'; + ELSIF v_elem ? 'ContinueAsNew' THEN + v_item_instance_id := v_elem->'ContinueAsNew'->>'instance'; + ELSIF v_elem ? 'TimerFired' THEN + v_item_instance_id := v_elem->'TimerFired'->>'instance'; + v_fire_at_ms := (v_elem->'TimerFired'->>'fire_at_ms')::BIGINT; + ELSIF v_elem ? 'ActivityCompleted' THEN + v_item_instance_id := v_elem->'ActivityCompleted'->>'instance'; + ELSIF v_elem ? 'ActivityFailed' THEN + v_item_instance_id := v_elem->'ActivityFailed'->>'instance'; + ELSIF v_elem ? 'ExternalRaised' THEN + v_item_instance_id := v_elem->'ExternalRaised'->>'instance'; + ELSIF v_elem ? 'CancelInstance' THEN + v_item_instance_id := v_elem->'CancelInstance'->>'instance'; + ELSIF v_elem ? 'SubOrchCompleted' THEN + v_item_instance_id := v_elem->'SubOrchCompleted'->>'parent_instance'; + ELSIF v_elem ? 'SubOrchFailed' THEN + v_item_instance_id := v_elem->'SubOrchFailed'->>'parent_instance'; + ELSIF v_elem ? 'QueueMessage' THEN + v_item_instance_id := v_elem->'QueueMessage'->>'instance'; + ELSE + v_item_instance_id := v_instance_id; + END IF; + + IF v_elem ? 'TimerFired' AND v_fire_at_ms IS NOT NULL AND v_fire_at_ms > 0 THEN + v_visible_at := TO_TIMESTAMP(v_fire_at_ms / 1000.0); + ELSE + v_visible_at := v_now_ts; + END IF; + + INSERT INTO %1$I.orchestrator_queue (instance_id, work_item, visible_at, created_at) + VALUES (v_item_instance_id, v_elem::TEXT, v_visible_at, v_now_ts); + + v_fire_at_ms := NULL; + END LOOP; + END IF; + + -- Step 11: Delete locked messages + DELETE FROM %1$I.orchestrator_queue q WHERE q.lock_token = p_lock_token; + + -- Step 12: Remove instance lock. If the lock is gone, it was released or + -- deleted after Step 1c; roll everything back rather than commit a turn + -- that no longer owns the instance. + DELETE FROM %1$I.instance_locks il + WHERE il.instance_id = v_instance_id AND il.lock_token = p_lock_token; + + GET DIAGNOSTICS v_rows_affected = ROW_COUNT; + + IF v_rows_affected = 0 THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + END; + $ack_orch$ LANGUAGE plpgsql; +$fmt$, v_schema_name); + + -- History.created_at used the same provider clock as the acknowledgement. + -- event_type can contain "Event", so inspect the serialized discriminator. + EXECUTE format($fmt$ + WITH completion_times AS ( + SELECT e.instance_id, e.execution_id, terminal.created_at + FROM %1$I.executions e + CROSS JOIN LATERAL ( + SELECT h.created_at FROM %1$I.history h + WHERE h.instance_id = e.instance_id AND h.execution_id = e.execution_id + AND h.event_data::jsonb->>'type' = 'OrchestrationContinuedAsNew' + ORDER BY h.event_id DESC LIMIT 1 + ) terminal + WHERE e.status = 'ContinuedAsNew' AND e.completed_at IS NULL + ) + UPDATE %1$I.executions e + SET completed_at = c.created_at + FROM completion_times c + WHERE e.instance_id = c.instance_id AND e.execution_id = c.execution_id + AND e.status = 'ContinuedAsNew' AND e.completed_at IS NULL +$fmt$, v_schema_name); + + EXECUTE format( + 'SELECT count(*) FROM %I.executions WHERE status = ''ContinuedAsNew'' AND completed_at IS NULL', + v_schema_name + ) INTO v_unresolved; + IF v_unresolved > 0 THEN + RAISE WARNING 'Migration 0027: % continued execution(s) in schema % have no terminal history timestamp; leaving completed_at NULL', + v_unresolved, v_schema_name; + END IF; +END $$; diff --git a/migrations/0027_diff.md b/migrations/0027_diff.md new file mode 100644 index 0000000..b77a05f --- /dev/null +++ b/migrations/0027_diff.md @@ -0,0 +1,318 @@ +# Diff for migration 0027 + +**Migration file:** `0027_continue_as_new_completed_at.sql` + +Each changed function is shown **in full** with `+`/`-` markers on changed lines. + +## Table Changes + +No structural changes. The migration backfills NULL completion timestamps for +continued executions from terminal history events. Unrecoverable rows remain +NULL and produce a warning; no executions or history are deleted. + +## New Indexes + +None. + +## Function Changes + +### `ack_orchestration_item` — Body Modified (baseline: 0026) + +Full function with diff: +```diff + CREATE OR REPLACE FUNCTION SCHEMA.ack_orchestration_item(p_lock_token text, p_now_ms bigint, p_execution_id bigint, p_history_delta jsonb, p_worker_items jsonb, p_orchestrator_items jsonb, p_metadata jsonb, p_cancelled_activities jsonb DEFAULT '[]'::jsonb) + RETURNS void + LANGUAGE plpgsql + AS $function$ + DECLARE + v_instance_id TEXT; + v_orchestration_name TEXT; + v_orchestration_version TEXT; + v_parent_instance_id TEXT; + v_status TEXT; + v_output TEXT; + v_completed_at TIMESTAMPTZ; + v_elem JSONB; + v_visible_at TIMESTAMPTZ; + v_fire_at_ms BIGINT; + v_item_instance_id TEXT; + v_item_execution_id BIGINT; + v_item_activity_id BIGINT; + v_item_session_id TEXT; + v_item_tag TEXT; + v_now_ts TIMESTAMPTZ; + v_custom_status_action TEXT; + v_custom_status_value TEXT; + v_current_execution_id BIGINT; + v_kv_mutations JSONB; + v_kv_item JSONB; + v_kv_action TEXT; + v_i INTEGER; + v_is_terminal BOOLEAN; + v_rows_affected INTEGER; + BEGIN + -- Convert Rust-supplied millisecond timestamp to TIMESTAMPTZ + v_now_ts := TO_TIMESTAMP(p_now_ms / 1000.0); + + -- Step 1: Validate lock token + SELECT il.instance_id INTO v_instance_id + FROM SCHEMA.instance_locks il + WHERE il.lock_token = p_lock_token AND il.locked_until > p_now_ms; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + + -- Step 1b: Take the advisory lock that fetch_orchestration_item takes + -- before it can take an instance over. Step 1 holds no lock, so a + -- fetch that judged the lease expired could otherwise replace the + -- token while this acknowledge runs. This acknowledge would then + -- commit its history and new work while its deletes below match no + -- rows, and the messages it processed would be delivered again. + PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); + + -- Step 1c: Revalidate the token after the wait. While this lock is + -- held, no fetch can replace it. + PERFORM 1 + FROM SCHEMA.instance_locks il + WHERE il.instance_id = v_instance_id + AND il.lock_token = p_lock_token; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + + -- Step 2: Extract metadata from JSONB + v_orchestration_name := p_metadata->>'orchestration_name'; + v_orchestration_version := p_metadata->>'orchestration_version'; + v_parent_instance_id := p_metadata->>'parent_instance_id'; + v_status := p_metadata->>'status'; + v_output := p_metadata->>'output'; + v_current_execution_id := p_execution_id; + v_is_terminal := v_status IN ('Completed', 'ContinuedAsNew', 'Failed'); + + -- Step 3: Create or update instance metadata (with explicit timestamps) + IF v_orchestration_name IS NOT NULL AND v_orchestration_version IS NOT NULL THEN + INSERT INTO SCHEMA.instances (instance_id, orchestration_name, orchestration_version, current_execution_id, parent_instance_id, created_at, updated_at) + VALUES (v_instance_id, v_orchestration_name, v_orchestration_version, p_execution_id, v_parent_instance_id, v_now_ts, v_now_ts) + ON CONFLICT (instance_id) DO NOTHING; + + UPDATE SCHEMA.instances i + SET orchestration_name = v_orchestration_name, + orchestration_version = v_orchestration_version, + parent_instance_id = COALESCE(i.parent_instance_id, v_parent_instance_id), + updated_at = v_now_ts + WHERE i.instance_id = v_instance_id; + END IF; + + -- Step 4: Create execution record (idempotent) + INSERT INTO SCHEMA.executions (instance_id, execution_id, status, started_at) + VALUES (v_instance_id, p_execution_id, 'Running', v_now_ts) + ON CONFLICT (instance_id, execution_id) DO NOTHING; + + -- Step 5: Update instance current_execution_id + UPDATE SCHEMA.instances i + SET current_execution_id = GREATEST(i.current_execution_id, p_execution_id), + updated_at = v_now_ts + WHERE i.instance_id = v_instance_id; + + -- Step 6: Append history_delta (batch insert with explicit timestamps) + IF p_history_delta IS NOT NULL AND JSONB_ARRAY_LENGTH(p_history_delta) > 0 THEN + INSERT INTO SCHEMA.history (instance_id, execution_id, event_id, event_type, event_data, created_at) + SELECT + v_instance_id, + p_execution_id, + (elem->>'event_id')::BIGINT, + elem->>'event_type', + elem->>'event_data', + v_now_ts + FROM JSONB_ARRAY_ELEMENTS(p_history_delta) AS elem; + END IF; + + -- Step 7: Update execution status if provided + IF v_status IS NOT NULL THEN + v_completed_at := CASE +- WHEN v_status IN ('Completed', 'Failed') THEN v_now_ts ++ WHEN v_is_terminal THEN v_now_ts + ELSE NULL + END; + + UPDATE SCHEMA.executions e + SET status = v_status, output = v_output, completed_at = v_completed_at + WHERE e.instance_id = v_instance_id AND e.execution_id = p_execution_id; + END IF; + + -- Step 7b: Store pinned duroxide version if provided in metadata + IF p_metadata ? 'pinned_duroxide_version' AND p_metadata->'pinned_duroxide_version' IS NOT NULL + AND p_metadata->>'pinned_duroxide_version' != 'null' THEN + UPDATE SCHEMA.executions + SET duroxide_version_major = (p_metadata->'pinned_duroxide_version'->>'major')::INTEGER, + duroxide_version_minor = (p_metadata->'pinned_duroxide_version'->>'minor')::INTEGER, + duroxide_version_patch = (p_metadata->'pinned_duroxide_version'->>'patch')::INTEGER + WHERE instance_id = v_instance_id AND execution_id = p_execution_id; + END IF; + + -- Step 7c: Handle custom_status update on instances table + v_custom_status_action := p_metadata->>'custom_status_action'; + IF v_custom_status_action = 'set' THEN + v_custom_status_value := p_metadata->>'custom_status_value'; + UPDATE SCHEMA.instances + SET custom_status = v_custom_status_value, + custom_status_version = custom_status_version + 1 + WHERE instance_id = v_instance_id; + ELSIF v_custom_status_action = 'clear' THEN + UPDATE SCHEMA.instances + SET custom_status = NULL, + custom_status_version = custom_status_version + 1 + WHERE instance_id = v_instance_id; + END IF; + + -- Step 7d: Materialize KV mutations into kv_delta only + v_kv_mutations := p_metadata->'kv_mutations'; + IF v_kv_mutations IS NOT NULL AND jsonb_array_length(v_kv_mutations) > 0 THEN + FOR v_i IN 0..jsonb_array_length(v_kv_mutations) - 1 LOOP + v_kv_item := v_kv_mutations->v_i; + v_kv_action := v_kv_item->>'action'; + IF v_kv_action = 'set' THEN + INSERT INTO SCHEMA.kv_delta (instance_id, key, value, last_updated_at_ms) + VALUES (v_instance_id, v_kv_item->>'key', v_kv_item->>'value', COALESCE((v_kv_item->>'last_updated_at_ms')::BIGINT, p_now_ms)) + ON CONFLICT (instance_id, key) + DO UPDATE SET value = EXCLUDED.value, last_updated_at_ms = EXCLUDED.last_updated_at_ms; + ELSIF v_kv_action = 'clear_key' THEN + INSERT INTO SCHEMA.kv_delta (instance_id, key, value, last_updated_at_ms) + VALUES (v_instance_id, v_kv_item->>'key', NULL, p_now_ms) + ON CONFLICT (instance_id, key) + DO UPDATE SET value = NULL, last_updated_at_ms = EXCLUDED.last_updated_at_ms; + ELSIF v_kv_action = 'clear_all' THEN + UPDATE SCHEMA.kv_delta + SET value = NULL, + last_updated_at_ms = p_now_ms + WHERE instance_id = v_instance_id; + + INSERT INTO SCHEMA.kv_delta (instance_id, key, value, last_updated_at_ms) + SELECT ks.instance_id, ks.key, NULL, p_now_ms + FROM SCHEMA.kv_store ks + WHERE ks.instance_id = v_instance_id + ON CONFLICT (instance_id, key) DO NOTHING; + END IF; + END LOOP; + END IF; + + -- Step 7e: Merge kv_delta into kv_store on terminal execution boundaries + IF v_is_terminal THEN + INSERT INTO SCHEMA.kv_store (instance_id, key, value, execution_id, last_updated_at_ms) + SELECT kd.instance_id, kd.key, kd.value, p_execution_id, kd.last_updated_at_ms + FROM SCHEMA.kv_delta kd + WHERE kd.instance_id = v_instance_id AND kd.value IS NOT NULL + ON CONFLICT (instance_id, key) + DO UPDATE SET value = EXCLUDED.value, + execution_id = EXCLUDED.execution_id, + last_updated_at_ms = EXCLUDED.last_updated_at_ms; + + DELETE FROM SCHEMA.kv_store ks + WHERE ks.instance_id = v_instance_id + AND ks.key IN ( + SELECT kd.key + FROM SCHEMA.kv_delta kd + WHERE kd.instance_id = v_instance_id + AND kd.value IS NULL + ); + + DELETE FROM SCHEMA.kv_delta kd + WHERE kd.instance_id = v_instance_id; + END IF; + + -- Step 8: Enqueue worker items with session_id and tag support + IF p_worker_items IS NOT NULL AND JSONB_ARRAY_LENGTH(p_worker_items) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_worker_items) LOOP + IF v_elem ? 'ActivityExecute' THEN + v_item_instance_id := v_elem->'ActivityExecute'->>'instance'; + v_item_execution_id := (v_elem->'ActivityExecute'->>'execution_id')::BIGINT; + v_item_activity_id := (v_elem->'ActivityExecute'->>'id')::BIGINT; + v_item_session_id := v_elem->'ActivityExecute'->>'session_id'; + v_item_tag := v_elem->'ActivityExecute'->>'tag'; + ELSE + v_item_instance_id := NULL; + v_item_execution_id := NULL; + v_item_activity_id := NULL; + v_item_session_id := NULL; + v_item_tag := NULL; + END IF; + + INSERT INTO SCHEMA.worker_queue (work_item, visible_at, created_at, instance_id, execution_id, activity_id, session_id, tag) + VALUES (v_elem::TEXT, v_now_ts, v_now_ts, v_item_instance_id, v_item_execution_id, v_item_activity_id, v_item_session_id, v_item_tag); + END LOOP; + END IF; + + -- Step 9: Delete cancelled activities from worker_queue (lock stealing) + IF p_cancelled_activities IS NOT NULL AND JSONB_ARRAY_LENGTH(p_cancelled_activities) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_cancelled_activities) LOOP + DELETE FROM SCHEMA.worker_queue + WHERE instance_id = v_elem->>'instance' + AND execution_id = (v_elem->>'execution_id')::BIGINT + AND activity_id = (v_elem->>'activity_id')::BIGINT; + END LOOP; + END IF; + + -- Step 10: Enqueue orchestrator items + IF p_orchestrator_items IS NOT NULL AND JSONB_ARRAY_LENGTH(p_orchestrator_items) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_orchestrator_items) LOOP + IF v_elem ? 'StartOrchestration' THEN + v_item_instance_id := v_elem->'StartOrchestration'->>'instance'; + ELSIF v_elem ? 'ContinueAsNew' THEN + v_item_instance_id := v_elem->'ContinueAsNew'->>'instance'; + ELSIF v_elem ? 'TimerFired' THEN + v_item_instance_id := v_elem->'TimerFired'->>'instance'; + v_fire_at_ms := (v_elem->'TimerFired'->>'fire_at_ms')::BIGINT; + ELSIF v_elem ? 'ActivityCompleted' THEN + v_item_instance_id := v_elem->'ActivityCompleted'->>'instance'; + ELSIF v_elem ? 'ActivityFailed' THEN + v_item_instance_id := v_elem->'ActivityFailed'->>'instance'; + ELSIF v_elem ? 'ExternalRaised' THEN + v_item_instance_id := v_elem->'ExternalRaised'->>'instance'; + ELSIF v_elem ? 'CancelInstance' THEN + v_item_instance_id := v_elem->'CancelInstance'->>'instance'; + ELSIF v_elem ? 'SubOrchCompleted' THEN + v_item_instance_id := v_elem->'SubOrchCompleted'->>'parent_instance'; + ELSIF v_elem ? 'SubOrchFailed' THEN + v_item_instance_id := v_elem->'SubOrchFailed'->>'parent_instance'; + ELSIF v_elem ? 'QueueMessage' THEN + v_item_instance_id := v_elem->'QueueMessage'->>'instance'; + ELSE + v_item_instance_id := v_instance_id; + END IF; + + IF v_elem ? 'TimerFired' AND v_fire_at_ms IS NOT NULL AND v_fire_at_ms > 0 THEN + v_visible_at := TO_TIMESTAMP(v_fire_at_ms / 1000.0); + ELSE + v_visible_at := v_now_ts; + END IF; + + INSERT INTO SCHEMA.orchestrator_queue (instance_id, work_item, visible_at, created_at) + VALUES (v_item_instance_id, v_elem::TEXT, v_visible_at, v_now_ts); + + v_fire_at_ms := NULL; + END LOOP; + END IF; + + -- Step 11: Delete locked messages + DELETE FROM SCHEMA.orchestrator_queue q WHERE q.lock_token = p_lock_token; + + -- Step 12: Remove instance lock. If the lock is gone, it was released or + -- deleted after Step 1c; roll everything back rather than commit a turn + -- that no longer owns the instance. + DELETE FROM SCHEMA.instance_locks il + WHERE il.instance_id = v_instance_id AND il.lock_token = p_lock_token; + + GET DIAGNOSTICS v_rows_affected = ROW_COUNT; + + IF v_rows_affected = 0 THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + END; + $function$ +\ No newline at end of file + +``` + +--- diff --git a/migrations/README.md b/migrations/README.md index 3114817..b6cfff6 100644 --- a/migrations/README.md +++ b/migrations/README.md @@ -90,6 +90,27 @@ CREATE INDEX IF NOT EXISTS idx_worker_processed ON worker_queue(processed_at); Migrations are automatically applied when creating a `PostgresProvider`. Each test schema gets its own migration history, so you can test migrations in isolation. +### Continued execution timestamps (0027) + +Migration `0027` fixes completion timestamps for `ContinuedAsNew` executions. +It preserves the acknowledgement lease safeguards introduced in migration `0026`. +It also fills existing NULL timestamps from the persisted `created_at` of each +execution's last `OrchestrationContinuedAsNew` history event. This uses the same +provider clock as acknowledgement, not the execution's start time or upgrade +time. Existing non-NULL timestamps and other execution statuses are unchanged. + +If no terminal event is available, the timestamp stays NULL and the migration +warns with the affected row count. These rows remain ineligible for age-based +pruning; inspect their history before choosing an explicit count-based policy. +The migration itself deletes no executions or history. Once timestamps are +recovered, subsequent age-based pruning can remove generations older than the +configured cutoff, while still protecting the current and running executions. + +Stop worker runtimes before upgrading and resume them after migrations complete, +so acknowledgements using the old function cannot race the one-time backfill. +The backfill can take time on a large history store. The migration is idempotent; +reapplying it does not change already populated timestamps. + ## Migration Execution Context - Migrations run inside transactions @@ -112,4 +133,3 @@ Migrations are automatically applied when creating a `PostgresProvider`. Each te ### Schema conflicts - Each schema maintains its own migration history - Migrations can be applied independently to different schemas - diff --git a/src/migrations.rs b/src/migrations.rs index 6f933f4..e29d120 100644 --- a/src/migrations.rs +++ b/src/migrations.rs @@ -8,6 +8,7 @@ use sqlx::PgPool; use std::collections::{HashMap, HashSet}; use std::sync::Arc; +// Touch this module when adding migrations so incremental builds re-embed them. Latest: 0027. static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations"); const BASE_TABLES: &[&str] = &[ diff --git a/tests/regression_tests.rs b/tests/regression_tests.rs index e0c82f3..da11246 100644 --- a/tests/regression_tests.rs +++ b/tests/regression_tests.rs @@ -6,6 +6,7 @@ //! Each test in this file reproduces a specific bug that was reported and fixed. //! These tests ensure the bugs don't regress. +use duroxide::providers::{InstanceFilter, Provider, PruneOptions}; use duroxide::runtime::registry::ActivityRegistry; use duroxide::runtime::{self, RuntimeOptions}; use duroxide::{ActivityContext, Client, OrchestrationContext, OrchestrationRegistry}; @@ -41,6 +42,306 @@ async fn cleanup_schema(schema_name: &str) { .expect("Failed to drop schema"); } +#[tokio::test] +async fn test_age_pruning_continue_as_new() { + verify_age_pruning(false).await; +} + +#[tokio::test] +async fn test_age_pruning_migrates_existing_history() { + verify_age_pruning(true).await; +} + +async fn verify_age_pruning(upgrade: bool) { + let schema = unique_schema_name(); + let database_url = get_database_url(); + let mut store = Arc::new( + PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .unwrap(), + ); + if upgrade { + // Generate real histories using the shipped acknowledgement function. + let mut tx = store.pool().begin().await.unwrap(); + sqlx::query(&format!("SET LOCAL search_path TO {schema}, pg_temp")) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::raw_sql(include_str!( + "../migrations/0026_serialize_orchestration_lock_mutations.sql" + )) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query(&format!( + "DELETE FROM {schema}._duroxide_migrations WHERE version >= 27" + )) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); + } + + let orchestrations = OrchestrationRegistry::builder() + .register( + "AgePruning", + |ctx: OrchestrationContext, input: String| async move { + let generation: u32 = input.parse().map_err(|error| format!("{error}"))?; + ctx.schedule_wait(format!("generation-{generation}")).await; + if generation < 3 { + ctx.continue_as_new((generation + 1).to_string()).await + } else { + Ok("done".to_string()) + } + }, + ) + .build(); + let options = RuntimeOptions { + dispatcher_min_poll_interval: Duration::from_millis(10), + ..Default::default() + }; + let mut runtime = runtime::Runtime::start_with_options( + store.clone(), + ActivityRegistry::builder().build(), + orchestrations.clone(), + options.clone(), + ) + .await; + let mut client = Client::new(store.clone()); + let instance = "age-pruning"; + client + .start_orchestration(instance, "AgePruning", "1") + .await + .unwrap(); + for generation in 1..=3 { + let signal = format!("generation-{generation}"); + assert!(common::wait_for_subscription(store.clone(), instance, &signal, 30_000).await); + if generation < 3 { + tokio::time::sleep(Duration::from_millis(10)).await; + client.raise_event(instance, &signal, "{}").await.unwrap(); + } + } + let old_history = store.read_with_execution(instance, 1).await.unwrap(); + let current_history = store.read_with_execution(instance, 3).await.unwrap(); + let times: Vec = sqlx::query_scalar(&format!( + "SELECT (extract(epoch FROM created_at)*1000)::bigint FROM {schema}.history + WHERE instance_id=$1 AND event_data::jsonb->>'type'='OrchestrationContinuedAsNew' + ORDER BY execution_id" + )) + .bind(instance) + .fetch_all(store.pool()) + .await + .unwrap(); + assert_eq!(times.len(), 2); + assert!(times[0] < times[1]); + let first_completed = u64::try_from(times[0]).unwrap(); + + if upgrade { + assert!(client + .get_execution_info(instance, 1) + .await + .unwrap() + .completed_at + .is_none()); + assert!(client + .get_execution_info(instance, 2) + .await + .unwrap() + .completed_at + .is_none()); + runtime.shutdown(Some(2_000)).await; + sqlx::raw_sql(&format!( + "INSERT INTO {schema}.instances + (instance_id,orchestration_name,current_execution_id,created_at,updated_at) + VALUES ('legacy-guards','AgePruning',6,now(),now()); + INSERT INTO {schema}.executions(instance_id,execution_id,status,started_at,completed_at) + SELECT 'legacy-guards',n, + CASE n WHEN 1 THEN 'ContinuedAsNew' WHEN 2 THEN 'Completed' + WHEN 3 THEN 'Failed' WHEN 5 THEN 'ContinuedAsNew' ELSE 'Running' END, + to_timestamp(0),CASE WHEN n=5 THEN to_timestamp(123) END + FROM generate_series(1,6) n; + INSERT INTO {schema}.history(instance_id,execution_id,event_id,event_type,event_data,created_at) + SELECT 'legacy-guards',n,1,'Event', + jsonb_build_object('type','OrchestrationContinuedAsNew')::text,to_timestamp(456) + FROM generate_series(2,5) n;" + )) + .execute(store.pool()) + .await + .unwrap(); + store = Arc::new( + PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .unwrap(), + ); + client = Client::new(store.clone()); + for _ in 0..2 { + let guarded: Vec> = sqlx::query_scalar(&format!( + "SELECT (extract(epoch FROM completed_at)*1000)::bigint FROM {schema}.executions + WHERE instance_id='legacy-guards' ORDER BY execution_id" + )) + .fetch_all(store.pool()) + .await + .unwrap(); + assert_eq!(guarded, [None, None, None, None, Some(123_000), None]); + assert_eq!( + store.read_with_execution(instance, 1).await.unwrap(), + old_history + ); + assert_eq!( + store.read_with_execution(instance, 3).await.unwrap(), + current_history + ); + assert_eq!( + client + .get_execution_info(instance, 1) + .await + .unwrap() + .completed_at, + Some(first_completed), + ); + let mut tx = store.pool().begin().await.unwrap(); + sqlx::query(&format!("SET LOCAL search_path TO {schema}, pg_temp")) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::raw_sql(include_str!( + "../migrations/0027_continue_as_new_completed_at.sql" + )) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); + } + runtime = runtime::Runtime::start_with_options( + store.clone(), + ActivityRegistry::builder().build(), + orchestrations.clone(), + options.clone(), + ) + .await; + } + + assert_eq!( + client + .get_execution_info(instance, 1) + .await + .unwrap() + .completed_at, + Some(first_completed), + ); + assert_eq!( + client + .get_execution_info(instance, 2) + .await + .unwrap() + .completed_at, + Some(u64::try_from(times[1]).unwrap()), + ); + assert!(client + .get_execution_info(instance, 3) + .await + .unwrap() + .completed_at + .is_none()); + let result = client + .prune_executions( + instance, + PruneOptions { + completed_before: Some(first_completed), + ..Default::default() + }, + ) + .await + .unwrap(); + assert_eq!(result.executions_deleted, 0, "the cutoff is exclusive"); + let result = client + .prune_executions( + instance, + PruneOptions { + keep_last: Some(3), + completed_before: Some(first_completed + 1), + }, + ) + .await + .unwrap(); + assert_eq!( + result.executions_deleted, 0, + "count and age filters must be ANDed" + ); + let result = client + .prune_executions_bulk( + InstanceFilter { + instance_ids: Some(vec![instance.to_string()]), + ..Default::default() + }, + PruneOptions { + keep_last: Some(2), + completed_before: Some(first_completed + 1), + }, + ) + .await + .unwrap(); + assert_eq!(result.instances_processed, 1); + assert_eq!(result.executions_deleted, 1); + assert_eq!( + result.events_deleted, + u64::try_from(old_history.len()).unwrap() + ); + let mut remaining = client.list_executions(instance).await.unwrap(); + remaining.sort_unstable(); + assert_eq!(remaining, [2, 3]); + assert_eq!( + store.read_with_execution(instance, 3).await.unwrap(), + current_history + ); + assert_eq!( + client.get_instance_info(instance).await.unwrap().status, + "Running" + ); + + // Restart to prove replay uses the retained history, not a cached execution. + runtime.shutdown(Some(2_000)).await; + let runtime = runtime::Runtime::start_with_options( + store.clone(), + ActivityRegistry::builder().build(), + orchestrations, + options, + ) + .await; + client + .raise_event(instance, "generation-3", "{}") + .await + .unwrap(); + client + .wait_for_orchestration(instance, Duration::from_secs(30)) + .await + .unwrap(); + let info = client.get_instance_info(instance).await.unwrap(); + assert_eq!(info.status, "Completed"); + assert_eq!(info.output.as_deref(), Some("done")); + let completed = client + .get_execution_info(instance, 3) + .await + .unwrap() + .completed_at + .unwrap(); + let result = client + .prune_executions( + instance, + PruneOptions { + completed_before: Some(completed + 1), + ..Default::default() + }, + ) + .await + .unwrap(); + assert_eq!(result.executions_deleted, 1); + assert_eq!(client.list_executions(instance).await.unwrap(), [3]); + runtime.shutdown(Some(2_000)).await; + cleanup_schema(&schema).await; + store.pool().close().await; +} + // ============================================================================= // Bug: Deadlock in fetch_orchestration_item during parallel sub-orchestrations // ============================================================================= From 3ed62ed14549f1571c4901ea5bb79a2c154bd791 Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Thu, 15 Oct 2026 17:05:08 +0000 Subject: [PATCH 02/10] Add bounded cursor-based pruning, and protect pending continuations from age-filtered bulk deletion Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 9 + migrations/0028_batched_execution_pruning.sql | 82 +++++ migrations/0028_diff.md | 79 +++++ migrations/README.md | 23 ++ src/migrations.rs | 2 +- src/provider.rs | 5 +- tests/execution_pruning_tests.rs | 286 ++++++++++++++++++ 7 files changed, 483 insertions(+), 3 deletions(-) create mode 100644 migrations/0028_batched_execution_pruning.sql create mode 100644 migrations/0028_diff.md create mode 100644 tests/execution_pruning_tests.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index ec0c1a3..2eedff9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,12 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Preserve pending continue-as-new instances in age-filtered bulk deletion. + Populating their completion timestamps no longer makes queued continuations + eligible for deletion. Unfiltered bulk deletion retains its existing behavior. - Record `completed_at` for `ContinuedAsNew` executions so age-based execution pruning also works for long-running workflows. Migration `0027` recovers missing timestamps from terminal history events without changing current execution protection. Rows without a recoverable terminal event remain NULL and produce a migration warning. +### Added + +- Migration `0028` adds the `prune_executions_batch` SQL API. It scans at most + 1,000 execution keys per call and returns a cursor even for protected or young + rows, allowing maintenance to make bounded progress without changing retention. + ## [0.1.38] - 2026-10-26 ### Fixed diff --git a/migrations/0028_batched_execution_pruning.sql b/migrations/0028_batched_execution_pruning.sql new file mode 100644 index 0000000..872f998 --- /dev/null +++ b/migrations/0028_batched_execution_pruning.sql @@ -0,0 +1,82 @@ +-- Copyright (c) Microsoft Corporation. +-- Licensed under the MIT License. + +-- Migration 0028: Bounded cursor-based execution pruning. +-- The page bounds scanned execution keys, including protected and young rows. +-- Callers advance using the returned key even when no execution was deleted. +DO $$ +DECLARE + v_schema_name TEXT := current_schema(); +BEGIN + EXECUTE format($fmt$ + CREATE OR REPLACE FUNCTION %1$I.prune_executions_batch( + p_after_instance_id TEXT, + p_after_execution_id BIGINT, + p_completed_before_ms BIGINT, + p_limit INTEGER + ) + RETURNS TABLE( + last_instance_id TEXT, + last_execution_id BIGINT, + executions_scanned BIGINT, + executions_deleted BIGINT, + events_deleted BIGINT + ) + LANGUAGE plpgsql + SET search_path = pg_catalog, pg_temp + AS $prune_batch$ + DECLARE + v_execution RECORD; + v_current_execution_id BIGINT; + v_count BIGINT; + BEGIN + IF p_after_instance_id IS NULL OR p_after_execution_id IS NULL + OR p_after_execution_id < 0 OR p_completed_before_ms IS NULL + OR p_completed_before_ms < 0 OR p_limit IS NULL + OR p_limit < 1 OR p_limit > 1000 THEN + RAISE EXCEPTION 'Invalid execution pruning cursor, cutoff, or limit (expected 1..1000)' + USING ERRCODE = '22023'; + END IF; + + executions_scanned := 0; + executions_deleted := 0; + events_deleted := 0; + FOR v_execution IN + SELECT e.instance_id, e.execution_id, e.status, e.completed_at + FROM %1$I.executions e + WHERE (e.instance_id, e.execution_id) > + (p_after_instance_id, p_after_execution_id) + ORDER BY e.instance_id, e.execution_id + LIMIT p_limit + LOOP + last_instance_id := v_execution.instance_id; + last_execution_id := v_execution.execution_id; + executions_scanned := executions_scanned + 1; + IF v_execution.status <> 'Running' + AND v_execution.completed_at < to_timestamp(p_completed_before_ms / 1000.0) THEN + SELECT i.current_execution_id INTO v_current_execution_id + FROM %1$I.instances i + WHERE i.instance_id = v_execution.instance_id; + + IF v_execution.execution_id < v_current_execution_id THEN + -- Exact-key deletes avoid plans that scan the entire history + -- table when joining a batch to its many history rows. + DELETE FROM %1$I.history h + WHERE h.instance_id = v_execution.instance_id + AND h.execution_id = v_execution.execution_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + events_deleted := events_deleted + v_count; + + DELETE FROM %1$I.executions e + WHERE e.instance_id = v_execution.instance_id + AND e.execution_id = v_execution.execution_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + executions_deleted := executions_deleted + v_count; + END IF; + END IF; + END LOOP; + RETURN NEXT; + END; + $prune_batch$; +$fmt$, v_schema_name); +END $$; diff --git a/migrations/0028_diff.md b/migrations/0028_diff.md new file mode 100644 index 0000000..44149ec --- /dev/null +++ b/migrations/0028_diff.md @@ -0,0 +1,79 @@ +# Diff for migration 0028 + +**Migration file:** `0028_batched_execution_pruning.sql` + +Each changed function is shown **in full** with `+`/`-` markers on changed lines. + +## Table Changes + +None. + +## New Indexes + +None. The cursor and per-generation deletes use existing primary keys. + +## Function Changes + +### `prune_executions_batch` — NEW +```sql +CREATE OR REPLACE FUNCTION SCHEMA.prune_executions_batch(p_after_instance_id text, p_after_execution_id bigint, p_completed_before_ms bigint, p_limit integer) + RETURNS TABLE(last_instance_id text, last_execution_id bigint, executions_scanned bigint, executions_deleted bigint, events_deleted bigint) + LANGUAGE plpgsql + SET search_path TO 'pg_catalog', 'pg_temp' +AS $function$ + DECLARE + v_execution RECORD; + v_current_execution_id BIGINT; + v_count BIGINT; + BEGIN + IF p_after_instance_id IS NULL OR p_after_execution_id IS NULL + OR p_after_execution_id < 0 OR p_completed_before_ms IS NULL + OR p_completed_before_ms < 0 OR p_limit IS NULL + OR p_limit < 1 OR p_limit > 1000 THEN + RAISE EXCEPTION 'Invalid execution pruning cursor, cutoff, or limit (expected 1..1000)' + USING ERRCODE = '22023'; + END IF; + + executions_scanned := 0; + executions_deleted := 0; + events_deleted := 0; + FOR v_execution IN + SELECT e.instance_id, e.execution_id, e.status, e.completed_at + FROM SCHEMA.executions e + WHERE (e.instance_id, e.execution_id) > + (p_after_instance_id, p_after_execution_id) + ORDER BY e.instance_id, e.execution_id + LIMIT p_limit + LOOP + last_instance_id := v_execution.instance_id; + last_execution_id := v_execution.execution_id; + executions_scanned := executions_scanned + 1; + IF v_execution.status <> 'Running' + AND v_execution.completed_at < to_timestamp(p_completed_before_ms / 1000.0) THEN + SELECT i.current_execution_id INTO v_current_execution_id + FROM SCHEMA.instances i + WHERE i.instance_id = v_execution.instance_id; + + IF v_execution.execution_id < v_current_execution_id THEN + -- Exact-key deletes avoid plans that scan the entire history + -- table when joining a batch to its many history rows. + DELETE FROM SCHEMA.history h + WHERE h.instance_id = v_execution.instance_id + AND h.execution_id = v_execution.execution_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + events_deleted := events_deleted + v_count; + + DELETE FROM SCHEMA.executions e + WHERE e.instance_id = v_execution.instance_id + AND e.execution_id = v_execution.execution_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + executions_deleted := executions_deleted + v_count; + END IF; + END IF; + END LOOP; + RETURN NEXT; + END; + $function$ +``` + +--- diff --git a/migrations/README.md b/migrations/README.md index b6cfff6..4a417c5 100644 --- a/migrations/README.md +++ b/migrations/README.md @@ -111,6 +111,29 @@ so acknowledgements using the old function cannot race the one-time backfill. The backfill can take time on a large history store. The migration is idempotent; reapplying it does not change already populated timestamps. +### Batched execution pruning (0028) + +`.prune_executions_batch(after_instance_id, after_execution_id, +completed_before_ms, limit)` atomically prunes one primary-key-ordered page across +the provider store. Start with `('', 0)`, a nonnegative epoch-millisecond cutoff, +and a limit from 1 through 1,000. It returns `last_instance_id`, +`last_execution_id`, `executions_scanned`, `executions_deleted`, and `events_deleted`. +Use the returned key to resume; both cursor columns are NULL only for an empty +page. A page shorter than the requested limit ends that scan. + +The limit applies to **scanned execution keys**, not just eligible matches. +Current/future executions, Running executions, and histories with NULL or recent +completion times are preserved, but still advance the cursor. Missing instance +metadata is not permission to delete history. No instance, queue, lock, or KV +records are removed. The number of history events per execution is not capped. + +Use a maintenance connection with appropriate statement/lock timeouts. A failed +call rolls back its entire batch. Applications that must progress past locked +pages may pre-read the bounded page's last key and retry that page on a later +scan; a successful call's cursor remains authoritative if concurrent work changes +the page. Keep the original `prune_executions` API for callers that intentionally +request a whole-instance historical cleanup. + ## Migration Execution Context - Migrations run inside transactions diff --git a/src/migrations.rs b/src/migrations.rs index e29d120..caebe9a 100644 --- a/src/migrations.rs +++ b/src/migrations.rs @@ -8,7 +8,7 @@ use sqlx::PgPool; use std::collections::{HashMap, HashSet}; use std::sync::Arc; -// Touch this module when adding migrations so incremental builds re-embed them. Latest: 0027. +// Touch this module when adding migrations so incremental builds re-embed them. Latest: 0028. static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations"); const BASE_TABLES: &[&str] = &[ diff --git a/src/provider.rs b/src/provider.rs index 6aa67b6..52a9be8 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -2654,7 +2654,8 @@ impl ProviderAdmin for PostgresProvider { )); } - // Add completed_before filter if provided + // A pending continuation is still a live instance. Before migration 0027 + // its NULL completed_at implicitly excluded it from age-based deletion. if filter.completed_before.is_some() { let param_num = filter .instance_ids @@ -2663,7 +2664,7 @@ impl ProviderAdmin for PostgresProvider { .unwrap_or(0) + 1; sql.push_str(&format!( - " AND e.completed_at < TO_TIMESTAMP(${} / 1000.0)", + " AND e.status OPERATOR(pg_catalog.=) ANY(ARRAY['Completed', 'Failed']) AND e.completed_at < TO_TIMESTAMP(${} / 1000.0)", param_num )); } diff --git a/tests/execution_pruning_tests.rs b/tests/execution_pruning_tests.rs new file mode 100644 index 0000000..6b24b78 --- /dev/null +++ b/tests/execution_pruning_tests.rs @@ -0,0 +1,286 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use duroxide::providers::{ExecutionMetadata, InstanceFilter, Provider, ProviderAdmin, WorkItem}; +use duroxide::{Client, Event, EventKind, OrchestrationStatus}; +use duroxide_pg::PostgresProvider; +use std::sync::Arc; +use std::time::Duration; + +type BatchResult = (Option, Option, i64, i64, i64); + +async fn provider() -> (Arc, String) { + dotenvy::dotenv().ok(); + let url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set"); + let schema = format!("pruning_{}", uuid::Uuid::new_v4().simple()); + let provider = PostgresProvider::new_with_schema(&url, Some(&schema)) + .await + .unwrap(); + (Arc::new(provider), schema) +} + +async fn cleanup(provider: &PostgresProvider, schema: &str) { + sqlx::query(&format!("DROP SCHEMA {schema} CASCADE")) + .execute(provider.pool()) + .await + .unwrap(); + provider.pool().close().await; +} + +#[tokio::test] +async fn batch_pruning_bounds_scanned_keys_and_rolls_back_atomically() { + let (provider, schema) = provider().await; + sqlx::raw_sql(&format!( + "INSERT INTO {schema}.instances + (instance_id,orchestration_name,current_execution_id,created_at,updated_at) + SELECT 'a'||lpad(n::text,4,'0'),'test',1,now(),now() FROM generate_series(1,1500) n; + INSERT INTO {schema}.instances + (instance_id,orchestration_name,current_execution_id,created_at,updated_at) + VALUES ('z','test',1201,now(),now()); + INSERT INTO {schema}.executions(instance_id,execution_id,status,started_at,completed_at) + SELECT instance_id,1,'Completed',to_timestamp(0),to_timestamp(1) FROM {schema}.instances + WHERE instance_id<>'z'; + INSERT INTO {schema}.executions(instance_id,execution_id,status,started_at,completed_at) + SELECT 'z',n,CASE WHEN n=1201 THEN 'Running' ELSE 'ContinuedAsNew' END, + to_timestamp(0),CASE WHEN n<1201 THEN to_timestamp(1) END FROM generate_series(1,1201) n; + INSERT INTO {schema}.history(instance_id,execution_id,event_id,event_type,event_data,created_at) + SELECT instance_id,execution_id,1,'Event','{{}}',now() FROM {schema}.executions;" + )).execute(provider.pool()).await.unwrap(); + let sql = format!("SELECT * FROM {schema}.prune_executions_batch($1,$2,$3,$4)"); + let mut hostile = provider.pool().begin().await.unwrap(); + sqlx::raw_sql(&format!( + "CREATE FUNCTION {schema}.to_timestamp(double precision) RETURNS timestamptz + LANGUAGE plpgsql AS $fn$ BEGIN RAISE EXCEPTION 'pruning function trap'; END $fn$; + SET LOCAL search_path={schema},pg_catalog; + CREATE TEMP TABLE type_anchor(id int); + CREATE DOMAIN pg_temp.text AS pg_catalog.text CHECK (false);" + )) + .execute(&mut *hostile) + .await + .unwrap(); + let first: BatchResult = sqlx::query_as(&sql) + .bind("") + .bind(0i64) + .bind(2000i64) + .bind(1000i32) + .fetch_one(&mut *hostile) + .await + .unwrap(); + assert_eq!(first, (Some("a1000".into()), Some(1), 1000, 0, 0)); + hostile.rollback().await.unwrap(); + + sqlx::raw_sql(&format!( + "CREATE FUNCTION {schema}.reject_prune() RETURNS trigger LANGUAGE plpgsql AS $fn$ + BEGIN IF OLD.instance_id='z' AND OLD.execution_id=3 THEN + RAISE EXCEPTION 'intentional batch failure'; + END IF; RETURN OLD; END $fn$; + CREATE TRIGGER reject_prune BEFORE DELETE ON {schema}.executions + FOR EACH ROW EXECUTE FUNCTION {schema}.reject_prune();" + )) + .execute(provider.pool()) + .await + .unwrap(); + let error = sqlx::query(&sql) + .bind("a1000") + .bind(1i64) + .bind(2000i64) + .bind(1000i32) + .execute(provider.pool()) + .await + .unwrap_err(); + assert!(error.to_string().contains("intentional batch failure")); + let counts: (i64, i64) = sqlx::query_as(&format!( + "SELECT (SELECT count(*) FROM {schema}.executions), (SELECT count(*) FROM {schema}.history)" + )) + .fetch_one(provider.pool()) + .await + .unwrap(); + assert_eq!( + counts, + (2701, 2701), + "no partial deletion may survive a failed batch" + ); + sqlx::query(&format!("DROP TRIGGER reject_prune ON {schema}.executions")) + .execute(provider.pool()) + .await + .unwrap(); + + let second: BatchResult = sqlx::query_as(&sql) + .bind("a1000") + .bind(1i64) + .bind(2000i64) + .bind(1000i32) + .fetch_one(provider.pool()) + .await + .unwrap(); + assert_eq!(second, (Some("z".into()), Some(500), 1000, 500, 500)); + let third: BatchResult = sqlx::query_as(&sql) + .bind("z") + .bind(500i64) + .bind(2000i64) + .bind(1000i32) + .fetch_one(provider.pool()) + .await + .unwrap(); + assert_eq!(third, (Some("z".into()), Some(1201), 701, 700, 700)); + let empty: BatchResult = sqlx::query_as(&sql) + .bind("z") + .bind(1201i64) + .bind(2000i64) + .bind(1000i32) + .fetch_one(provider.pool()) + .await + .unwrap(); + assert_eq!(empty, (None, None, 0, 0, 0)); + assert_eq!( + provider.get_execution_info("z", 1201).await.unwrap().status, + "Running" + ); + for invalid_limit in [0, 1001] { + let error = sqlx::query(&sql) + .bind("") + .bind(0i64) + .bind(2000i64) + .bind(invalid_limit) + .execute(provider.pool()) + .await + .unwrap_err(); + assert_eq!( + error.as_database_error().unwrap().code().as_deref(), + Some("22023") + ); + } + cleanup(&provider, &schema).await; +} + +#[tokio::test] +async fn age_filtered_bulk_delete_preserves_queued_continuation() { + let (provider, schema) = provider().await; + let client = Client::new(provider.clone()); + for status in ["Completed", "Running", "ContinuedAsNew"] { + client + .start_orchestration(status, "test", "{}") + .await + .unwrap(); + let (_, token, _) = provider + .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None) + .await + .unwrap() + .unwrap(); + let mut history = vec![Event::with_event_id( + 1, + status, + 1, + None, + EventKind::OrchestrationStarted { + name: "test".into(), + version: "1.0.0".into(), + input: "{}".into(), + parent_instance: None, + parent_id: None, + parent_execution_id: None, + carry_forward_events: None, + initial_custom_status: None, + }, + )]; + let mut followup = Vec::new(); + if status == "ContinuedAsNew" { + history.push(Event::with_event_id( + 2, + status, + 1, + None, + EventKind::OrchestrationContinuedAsNew { + input: "next".into(), + }, + )); + followup.push(WorkItem::ContinueAsNew { + instance: status.into(), + orchestration: "test".into(), + input: "next".into(), + version: Some("1.0.0".into()), + parent_instance: None, + parent_id: None, + parent_execution_id: None, + carry_forward_events: vec![], + initial_custom_status: None, + }); + } else if status == "Completed" { + history.push(Event::with_event_id( + 2, + status, + 1, + None, + EventKind::OrchestrationCompleted { + output: "done".into(), + }, + )); + } + provider + .ack_orchestration_item( + &token, + 1, + history, + vec![], + followup, + ExecutionMetadata { + status: Some(status.into()), + orchestration_name: Some("test".into()), + orchestration_version: Some("1.0.0".into()), + ..Default::default() + }, + vec![], + ) + .await + .unwrap(); + } + let cutoff = u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap() + 1; + let deleted = client + .delete_instance_bulk(InstanceFilter { + completed_before: Some(cutoff), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(deleted.instances_deleted, 1); + assert!(matches!( + client + .get_orchestration_status("ContinuedAsNew") + .await + .unwrap(), + OrchestrationStatus::Running { .. } + )); + assert_eq!( + provider + .get_execution_info("Running", 1) + .await + .unwrap() + .status, + "Running" + ); + let (item, token, _) = provider + .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None) + .await + .unwrap() + .expect("continuation must remain fetchable"); + assert_eq!(item.instance, "ContinuedAsNew"); + assert!(item.messages.iter().any( + |message| matches!(message, WorkItem::ContinueAsNew { input, .. } if input == "next") + )); + provider + .abandon_orchestration_item(&token, None, false) + .await + .unwrap(); + let unfiltered = client + .delete_instance_bulk(InstanceFilter { + instance_ids: Some(vec!["ContinuedAsNew".into()]), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!( + unfiltered.instances_deleted, 1, + "unfiltered deletion retains its existing behavior" + ); + cleanup(&provider, &schema).await; +} From acfb3fd197f6a72b6c48c5ade2ef0c677a65afbf Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Thu, 29 Oct 2026 14:53:01 +0000 Subject: [PATCH 03/10] Address review feedback --- CHANGELOG.md | 2 + migrations/0028_batched_execution_pruning.sql | 52 +++--- migrations/0028_diff.md | 52 +++--- migrations/README.md | 5 + src/migrations.rs | 2 +- tests/deadlocks/main.rs | 3 + tests/deadlocks/pruning.rs | 155 ++++++++++++++++++ tests/execution_pruning_tests.rs | 69 ++++++++ 8 files changed, 299 insertions(+), 41 deletions(-) create mode 100644 tests/deadlocks/pruning.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 2eedff9..9936738 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Migration `0028` adds the `prune_executions_batch` SQL API. It scans at most 1,000 execution keys per call and returns a cursor even for protected or young rows, allowing maintenance to make bounded progress without changing retention. + Pruning serializes with instance deletion and execution updates, then rechecks + eligibility to protect replacement instances. ## [0.1.38] - 2026-10-26 diff --git a/migrations/0028_batched_execution_pruning.sql b/migrations/0028_batched_execution_pruning.sql index 872f998..d765f62 100644 --- a/migrations/0028_batched_execution_pruning.sql +++ b/migrations/0028_batched_execution_pruning.sql @@ -42,7 +42,7 @@ BEGIN executions_deleted := 0; events_deleted := 0; FOR v_execution IN - SELECT e.instance_id, e.execution_id, e.status, e.completed_at + SELECT e.instance_id, e.execution_id FROM %1$I.executions e WHERE (e.instance_id, e.execution_id) > (p_after_instance_id, p_after_execution_id) @@ -52,28 +52,40 @@ BEGIN last_instance_id := v_execution.instance_id; last_execution_id := v_execution.execution_id; executions_scanned := executions_scanned + 1; - IF v_execution.status <> 'Running' - AND v_execution.completed_at < to_timestamp(p_completed_before_ms / 1000.0) THEN - SELECT i.current_execution_id INTO v_current_execution_id - FROM %1$I.instances i - WHERE i.instance_id = v_execution.instance_id; + -- Lock before touching history, as deletion does. The page may + -- describe an earlier lifetime of the same instance/execution key. + SELECT i.current_execution_id INTO v_current_execution_id + FROM %1$I.instances i + WHERE i.instance_id = v_execution.instance_id + FOR NO KEY UPDATE; - IF v_execution.execution_id < v_current_execution_id THEN - -- Exact-key deletes avoid plans that scan the entire history - -- table when joining a batch to its many history rows. - DELETE FROM %1$I.history h - WHERE h.instance_id = v_execution.instance_id - AND h.execution_id = v_execution.execution_id; - GET DIAGNOSTICS v_count = ROW_COUNT; - events_deleted := events_deleted + v_count; + IF NOT FOUND OR v_execution.execution_id >= v_current_execution_id THEN + CONTINUE; + END IF; - DELETE FROM %1$I.executions e - WHERE e.instance_id = v_execution.instance_id - AND e.execution_id = v_execution.execution_id; - GET DIAGNOSTICS v_count = ROW_COUNT; - executions_deleted := executions_deleted + v_count; - END IF; + -- Eligibility may have changed while waiting for the instance lock. + PERFORM 1 FROM %1$I.executions e + WHERE e.instance_id = v_execution.instance_id + AND e.execution_id = v_execution.execution_id + AND e.status <> 'Running' + AND e.completed_at < to_timestamp(p_completed_before_ms / 1000.0); + IF NOT FOUND THEN + CONTINUE; END IF; + + -- Exact-key deletes avoid plans that scan the entire history + -- table when joining a batch to its many history rows. + DELETE FROM %1$I.history h + WHERE h.instance_id = v_execution.instance_id + AND h.execution_id = v_execution.execution_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + events_deleted := events_deleted + v_count; + + DELETE FROM %1$I.executions e + WHERE e.instance_id = v_execution.instance_id + AND e.execution_id = v_execution.execution_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + executions_deleted := executions_deleted + v_count; END LOOP; RETURN NEXT; END; diff --git a/migrations/0028_diff.md b/migrations/0028_diff.md index 44149ec..dbfb66d 100644 --- a/migrations/0028_diff.md +++ b/migrations/0028_diff.md @@ -38,7 +38,7 @@ AS $function$ executions_deleted := 0; events_deleted := 0; FOR v_execution IN - SELECT e.instance_id, e.execution_id, e.status, e.completed_at + SELECT e.instance_id, e.execution_id FROM SCHEMA.executions e WHERE (e.instance_id, e.execution_id) > (p_after_instance_id, p_after_execution_id) @@ -48,28 +48,40 @@ AS $function$ last_instance_id := v_execution.instance_id; last_execution_id := v_execution.execution_id; executions_scanned := executions_scanned + 1; - IF v_execution.status <> 'Running' - AND v_execution.completed_at < to_timestamp(p_completed_before_ms / 1000.0) THEN - SELECT i.current_execution_id INTO v_current_execution_id - FROM SCHEMA.instances i - WHERE i.instance_id = v_execution.instance_id; + -- Lock before touching history, as deletion does. The page may + -- describe an earlier lifetime of the same instance/execution key. + SELECT i.current_execution_id INTO v_current_execution_id + FROM SCHEMA.instances i + WHERE i.instance_id = v_execution.instance_id + FOR NO KEY UPDATE; - IF v_execution.execution_id < v_current_execution_id THEN - -- Exact-key deletes avoid plans that scan the entire history - -- table when joining a batch to its many history rows. - DELETE FROM SCHEMA.history h - WHERE h.instance_id = v_execution.instance_id - AND h.execution_id = v_execution.execution_id; - GET DIAGNOSTICS v_count = ROW_COUNT; - events_deleted := events_deleted + v_count; + IF NOT FOUND OR v_execution.execution_id >= v_current_execution_id THEN + CONTINUE; + END IF; - DELETE FROM SCHEMA.executions e - WHERE e.instance_id = v_execution.instance_id - AND e.execution_id = v_execution.execution_id; - GET DIAGNOSTICS v_count = ROW_COUNT; - executions_deleted := executions_deleted + v_count; - END IF; + -- Eligibility may have changed while waiting for the instance lock. + PERFORM 1 FROM SCHEMA.executions e + WHERE e.instance_id = v_execution.instance_id + AND e.execution_id = v_execution.execution_id + AND e.status <> 'Running' + AND e.completed_at < to_timestamp(p_completed_before_ms / 1000.0); + IF NOT FOUND THEN + CONTINUE; END IF; + + -- Exact-key deletes avoid plans that scan the entire history + -- table when joining a batch to its many history rows. + DELETE FROM SCHEMA.history h + WHERE h.instance_id = v_execution.instance_id + AND h.execution_id = v_execution.execution_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + events_deleted := events_deleted + v_count; + + DELETE FROM SCHEMA.executions e + WHERE e.instance_id = v_execution.instance_id + AND e.execution_id = v_execution.execution_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + executions_deleted := executions_deleted + v_count; END LOOP; RETURN NEXT; END; diff --git a/migrations/README.md b/migrations/README.md index 4a417c5..d65533a 100644 --- a/migrations/README.md +++ b/migrations/README.md @@ -127,6 +127,11 @@ completion times are preserved, but still advance the cursor. Missing instance metadata is not permission to delete history. No instance, queue, lock, or KV records are removed. The number of history events per execution is not capped. +Batches hold instance-row locks until their transaction ends and recheck +execution eligibility after any lock wait. This serializes pruning with instance +deletion/recreation and acknowledgement, protecting replacement instances and +executions that become ineligible while the batch waits. + Use a maintenance connection with appropriate statement/lock timeouts. A failed call rolls back its entire batch. Applications that must progress past locked pages may pre-read the bounded page's last key and retry that page on a later diff --git a/src/migrations.rs b/src/migrations.rs index caebe9a..f6577bd 100644 --- a/src/migrations.rs +++ b/src/migrations.rs @@ -8,7 +8,7 @@ use sqlx::PgPool; use std::collections::{HashMap, HashSet}; use std::sync::Arc; -// Touch this module when adding migrations so incremental builds re-embed them. Latest: 0028. +// Touch this module when changing migrations so incremental builds re-embed them. Latest: 0028. static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations"); const BASE_TABLES: &[&str] = &[ diff --git a/tests/deadlocks/main.rs b/tests/deadlocks/main.rs index fbaaee6..d3cf755 100644 --- a/tests/deadlocks/main.rs +++ b/tests/deadlocks/main.rs @@ -29,6 +29,7 @@ //! (migration 0026). //! - `renew_fetch`: renewal against fetch, forced and raced (migration 0026). //! - `renew_ack_abandon`: renewal against acknowledge and abandon. +//! - `pruning`: batch pruning against deletion/recreation and execution updates. //! - `victim_retry`: the provider retries a renewal aborted as a deadlock //! victim. //! - `harness`: shared helpers, also used by @@ -37,6 +38,7 @@ mod ack_fetch; mod harness; +mod pruning; mod renew_ack_abandon; mod renew_fetch; mod victim_retry; @@ -46,6 +48,7 @@ const SOURCES: &[(&str, &str)] = &[ ("main.rs", include_str!("main.rs")), ("ack_fetch.rs", include_str!("ack_fetch.rs")), ("harness.rs", include_str!("harness.rs")), + ("pruning.rs", include_str!("pruning.rs")), ("renew_ack_abandon.rs", include_str!("renew_ack_abandon.rs")), ("renew_fetch.rs", include_str!("renew_fetch.rs")), ("victim_retry.rs", include_str!("victim_retry.rs")), diff --git a/tests/deadlocks/pruning.rs b/tests/deadlocks/pruning.rs new file mode 100644 index 0000000..652e8c2 --- /dev/null +++ b/tests/deadlocks/pruning.rs @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use crate::harness::*; +use duroxide_pg::PostgresProvider; +use serde_json::Value; +use sqlx::{PgConnection, PgPool}; + +type BatchResult = (Option, Option, i64, i64, i64); + +async fn seed_instance(schema: &str) -> PostgresProvider { + let provider = PostgresProvider::new_with_schema(&database_url(), Some(schema)) + .await + .expect("failed to create provider"); + sqlx::Executor::execute( + provider.pool(), + format!( + "INSERT INTO {schema}.instances + (instance_id, orchestration_name, current_execution_id, created_at, updated_at) + VALUES ('pruning-race', 'test', 2, to_timestamp(0), to_timestamp(0)); + INSERT INTO {schema}.executions + (instance_id, execution_id, status, started_at, completed_at) + VALUES ('pruning-race', 1, 'ContinuedAsNew', to_timestamp(0), to_timestamp(1)), + ('pruning-race', 2, 'Running', to_timestamp(1), NULL); + INSERT INTO {schema}.history + (instance_id, execution_id, event_id, event_type, event_data, created_at) + SELECT 'pruning-race', n, 1, 'Event', 'original', to_timestamp(0) + FROM generate_series(1, 2) n;" + ) + .as_str(), + ) + .await + .expect("failed to seed pruning history"); + provider +} + +async fn durable_state(connection: &mut PgConnection, schema: &str) -> Value { + sqlx::query_scalar(&format!( + "SELECT jsonb_build_object( + 'instances', (SELECT jsonb_agg(i ORDER BY i.instance_id) + FROM {schema}.instances i), + 'executions', (SELECT jsonb_agg(e ORDER BY e.instance_id, e.execution_id) + FROM {schema}.executions e), + 'history', (SELECT jsonb_agg(h ORDER BY h.instance_id, h.execution_id, h.event_id) + FROM {schema}.history h))" + )) + .fetch_one(connection) + .await + .expect("failed to snapshot durable state") +} + +async fn prune_batch(pool: PgPool, schema: String) -> Result { + let mut tx = pool.begin().await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL READ COMMITTED") + .execute(&mut *tx) + .await?; + let result = sqlx::query_as(&format!( + "SELECT * FROM {schema}.prune_executions_batch('', 0, 2000, 10)" + )) + .fetch_one(&mut *tx) + .await?; + tx.commit().await?; + Ok(result) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn batch_pruning_preserves_a_deleted_and_recreated_instance() { + with_schema(|schema| async move { + let provider = seed_instance(&schema).await; + let mut replacement = provider.pool().begin().await.unwrap(); + let deleted: (i64, i64, i64, i64) = sqlx::query_as(&format!( + "SELECT * FROM {schema}.delete_instances_atomic(ARRAY['pruning-race'], TRUE)" + )) + .fetch_one(&mut *replacement) + .await + .expect("failed to delete the original instance"); + assert_eq!(deleted, (1, 2, 2, 0)); + sqlx::Executor::execute( + &mut *replacement, + format!( + "INSERT INTO {schema}.instances + (instance_id, orchestration_name, current_execution_id, created_at, updated_at) + VALUES ('pruning-race', 'replacement', 1, to_timestamp(3), to_timestamp(3)); + INSERT INTO {schema}.executions + (instance_id, execution_id, status, started_at, completed_at) + VALUES ('pruning-race', 1, 'Running', to_timestamp(3), NULL); + INSERT INTO {schema}.history + (instance_id, execution_id, event_id, event_type, event_data, created_at) + VALUES ('pruning-race', 1, 1, 'Event', 'replacement', to_timestamp(3));" + ) + .as_str(), + ) + .await + .expect("failed to recreate the instance"); + let before = durable_state(&mut replacement, &schema).await; + + // The page sees the old committed lifetime while its replacement is uncommitted. + let prune = tokio::spawn(prune_batch(provider.pool().clone(), schema.clone())); + wait_for_call_to_wait(provider.pool(), &schema, "prune_executions_batch", false).await; + timed("replacement commit", replacement.commit()) + .await + .unwrap(); + let result = timed("batch pruning", prune).await.unwrap(); + assert_not_deadlock_victim("batch pruning", &result); + let result = result.expect("batch pruning must succeed"); + + let mut connection = provider.pool().acquire().await.unwrap(); + assert_eq!( + durable_state(&mut connection, &schema).await, + before, + "a stale page must not delete the replacement's current execution or history" + ); + assert_eq!(result, (Some("pruning-race".into()), Some(2), 2, 0, 0)); + }) + .await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn batch_pruning_rechecks_eligibility_after_an_instance_lock_wait() { + with_schema(|schema| async move { + let provider = seed_instance(&schema).await; + let mut update = provider.pool().begin().await.unwrap(); + sqlx::Executor::execute( + &mut *update, + format!( + "UPDATE {schema}.instances SET updated_at = to_timestamp(3) + WHERE instance_id = 'pruning-race'; + UPDATE {schema}.executions SET status = 'Running' + WHERE instance_id = 'pruning-race' AND execution_id = 1;" + ) + .as_str(), + ) + .await + .expect("failed to update execution eligibility"); + let before = durable_state(&mut update, &schema).await; + + let prune = tokio::spawn(prune_batch(provider.pool().clone(), schema.clone())); + wait_for_call_to_wait(provider.pool(), &schema, "prune_executions_batch", false).await; + timed("execution update commit", update.commit()) + .await + .unwrap(); + let result = timed("batch pruning", prune).await.unwrap(); + assert_not_deadlock_victim("batch pruning", &result); + let result = result.expect("batch pruning must succeed"); + + let mut connection = provider.pool().acquire().await.unwrap(); + assert_eq!( + durable_state(&mut connection, &schema).await, + before, + "eligibility must be read again after the instance lock is acquired" + ); + assert_eq!(result, (Some("pruning-race".into()), Some(2), 2, 0, 0)); + }) + .await; +} diff --git a/tests/execution_pruning_tests.rs b/tests/execution_pruning_tests.rs index 6b24b78..172ab4b 100644 --- a/tests/execution_pruning_tests.rs +++ b/tests/execution_pruning_tests.rs @@ -153,6 +153,75 @@ async fn batch_pruning_bounds_scanned_keys_and_rolls_back_atomically() { cleanup(&provider, &schema).await; } +#[tokio::test] +async fn batch_pruning_independently_protects_ineligible_executions() { + let (provider, schema) = provider().await; + sqlx::raw_sql(&format!( + "INSERT INTO {schema}.instances + (instance_id, orchestration_name, current_execution_id, created_at, updated_at) + VALUES ('eligibility', 'test', 6, to_timestamp(0), to_timestamp(0)); + INSERT INTO {schema}.executions + (instance_id, execution_id, status, started_at, completed_at) + VALUES ('eligibility', 1, 'Running', to_timestamp(0), to_timestamp(1)), + ('eligibility', 2, 'ContinuedAsNew', to_timestamp(0), NULL), + ('eligibility', 3, 'Completed', to_timestamp(0), to_timestamp(2)), + ('eligibility', 4, 'Failed', to_timestamp(0), to_timestamp(3)), + ('eligibility', 5, 'ContinuedAsNew', to_timestamp(0), to_timestamp(1)), + ('eligibility', 6, 'Completed', to_timestamp(0), to_timestamp(1)), + ('eligibility', 7, 'Completed', to_timestamp(0), to_timestamp(1)); + INSERT INTO {schema}.history + (instance_id, execution_id, event_id, event_type, event_data, created_at) + SELECT 'eligibility', n, 1, 'Event', '{{}}', to_timestamp(0) + FROM generate_series(1, 7) n;" + )) + .execute(provider.pool()) + .await + .unwrap(); + let protected_sql = format!( + "SELECT e.execution_id, to_jsonb(e), to_jsonb(h) + FROM {schema}.executions e JOIN {schema}.history h + USING (instance_id, execution_id) + WHERE e.execution_id <> 5 ORDER BY e.execution_id, h.event_id" + ); + let before: Vec<(i64, serde_json::Value, serde_json::Value)> = sqlx::query_as(&protected_sql) + .fetch_all(provider.pool()) + .await + .unwrap(); + assert_eq!(before.len(), 6); + let sql = format!("SELECT * FROM {schema}.prune_executions_batch($1, $2, 2000, 1)"); + let mut cursor = (String::new(), 0i64); + for expected_id in 1..=7 { + let result: BatchResult = sqlx::query_as(&sql) + .bind(&cursor.0) + .bind(cursor.1) + .fetch_one(provider.pool()) + .await + .unwrap(); + let deleted = if expected_id == 5 { 1 } else { 0 }; + assert_eq!( + result, + ( + Some("eligibility".into()), + Some(expected_id), + 1, + deleted, + deleted + ), + "only the eligible historical execution may be pruned" + ); + cursor = (result.0.unwrap(), result.1.unwrap()); + } + let after: Vec<(i64, serde_json::Value, serde_json::Value)> = sqlx::query_as(&protected_sql) + .fetch_all(provider.pool()) + .await + .unwrap(); + assert_eq!( + after, before, + "protected executions and histories must not change" + ); + cleanup(&provider, &schema).await; +} + #[tokio::test] async fn age_filtered_bulk_delete_preserves_queued_continuation() { let (provider, schema) = provider().await; From 889828a15d3c3dd0b5bd43238b7d5bebb077912e Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Thu, 29 Oct 2026 15:44:45 +0000 Subject: [PATCH 04/10] Fix lock order issue --- CHANGELOG.md | 2 + migrations/0028_batched_execution_pruning.sql | 98 +++++++++++++++++ migrations/0028_diff.md | 95 ++++++++++++++++ migrations/README.md | 2 + src/migrations.rs | 3 +- tests/deadlocks/pruning.rs | 103 ++++++++++++++++-- 6 files changed, 291 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9936738..c0836cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 rows, allowing maintenance to make bounded progress without changing retention. Pruning serializes with instance deletion and execution updates, then rechecks eligibility to protect replacement instances. + Atomic deletion uses the same instance-ID lock order to prevent multi-instance + deadlocks with pruning. ## [0.1.38] - 2026-10-26 diff --git a/migrations/0028_batched_execution_pruning.sql b/migrations/0028_batched_execution_pruning.sql index d765f62..a8a8213 100644 --- a/migrations/0028_batched_execution_pruning.sql +++ b/migrations/0028_batched_execution_pruning.sql @@ -91,4 +91,102 @@ BEGIN END; $prune_batch$; $fmt$, v_schema_name); + + -- Both procedures retain instance locks until commit, so they must acquire + -- them in the same order. The deletion body is otherwise unchanged from 0020. + EXECUTE format($fmt$ + CREATE OR REPLACE FUNCTION %1$I.delete_instances_atomic( + p_instance_ids TEXT[], + p_force BOOLEAN + ) + RETURNS TABLE( + instances_deleted BIGINT, + executions_deleted BIGINT, + events_deleted BIGINT, + queue_messages_deleted BIGINT + ) AS $delete_atomic$ + DECLARE + v_instance_id TEXT; + v_orphan_id TEXT; + v_instances_deleted BIGINT := 0; + v_executions_deleted BIGINT := 0; + v_events_deleted BIGINT := 0; + v_queue_deleted BIGINT := 0; + v_count BIGINT; + BEGIN + -- Check for empty input + IF p_instance_ids IS NULL OR array_length(p_instance_ids, 1) IS NULL THEN + instances_deleted := 0; + executions_deleted := 0; + events_deleted := 0; + queue_messages_deleted := 0; + RETURN NEXT; + RETURN; + END IF; + + -- Step 1: If not force, check all instances are terminal (single query, no loop) + IF NOT p_force THEN + SELECT i.instance_id INTO v_instance_id + FROM %1$I.instances i + JOIN %1$I.executions e ON i.instance_id = e.instance_id + AND i.current_execution_id = e.execution_id + WHERE i.instance_id = ANY(p_instance_ids) + AND e.status = 'Running' + LIMIT 1; + + IF v_instance_id IS NOT NULL THEN + RAISE EXCEPTION 'Instance %% is Running. Use force=true to delete.', v_instance_id; + END IF; + END IF; + + -- Step 2: Lock parent rows to prevent concurrent child creation + PERFORM 1 FROM %1$I.instances + WHERE instance_id = ANY(p_instance_ids) + ORDER BY instance_id + FOR UPDATE; + + -- Step 3: Check for orphans (children not in our delete list) + SELECT i.instance_id INTO v_orphan_id + FROM %1$I.instances i + WHERE i.parent_instance_id = ANY(p_instance_ids) + AND NOT (i.instance_id = ANY(p_instance_ids)) + LIMIT 1; + + IF v_orphan_id IS NOT NULL THEN + RAISE EXCEPTION 'Orphan detected: instance %% has parent in delete list but is not included', v_orphan_id; + END IF; + + -- Step 4: Delete from all tables + DELETE FROM %1$I.history WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_events_deleted := v_count; + + DELETE FROM %1$I.executions WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_executions_deleted := v_count; + + DELETE FROM %1$I.orchestrator_queue WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_queue_deleted := v_count; + + DELETE FROM %1$I.worker_queue WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_queue_deleted := v_queue_deleted + v_count; + + DELETE FROM %1$I.instance_locks WHERE instance_id = ANY(p_instance_ids); + DELETE FROM %1$I.kv_delta WHERE instance_id = ANY(p_instance_ids); + DELETE FROM %1$I.kv_store WHERE instance_id = ANY(p_instance_ids); + + DELETE FROM %1$I.instances WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_instances_deleted := v_count; + + instances_deleted := v_instances_deleted; + executions_deleted := v_executions_deleted; + events_deleted := v_events_deleted; + queue_messages_deleted := v_queue_deleted; + RETURN NEXT; + END; + $delete_atomic$ LANGUAGE plpgsql; +$fmt$, v_schema_name); END $$; diff --git a/migrations/0028_diff.md b/migrations/0028_diff.md index dbfb66d..362d1cc 100644 --- a/migrations/0028_diff.md +++ b/migrations/0028_diff.md @@ -14,6 +14,101 @@ None. The cursor and per-generation deletes use existing primary keys. ## Function Changes +### `delete_instances_atomic` — Body Modified (baseline: 0020) + +Full function with diff: +```diff + CREATE OR REPLACE FUNCTION SCHEMA.delete_instances_atomic(p_instance_ids text[], p_force boolean) + RETURNS TABLE(instances_deleted bigint, executions_deleted bigint, events_deleted bigint, queue_messages_deleted bigint) + LANGUAGE plpgsql + AS $function$ + DECLARE + v_instance_id TEXT; + v_orphan_id TEXT; + v_instances_deleted BIGINT := 0; + v_executions_deleted BIGINT := 0; + v_events_deleted BIGINT := 0; + v_queue_deleted BIGINT := 0; + v_count BIGINT; + BEGIN + -- Check for empty input + IF p_instance_ids IS NULL OR array_length(p_instance_ids, 1) IS NULL THEN + instances_deleted := 0; + executions_deleted := 0; + events_deleted := 0; + queue_messages_deleted := 0; + RETURN NEXT; + RETURN; + END IF; + + -- Step 1: If not force, check all instances are terminal (single query, no loop) + IF NOT p_force THEN + SELECT i.instance_id INTO v_instance_id + FROM SCHEMA.instances i + JOIN SCHEMA.executions e ON i.instance_id = e.instance_id + AND i.current_execution_id = e.execution_id + WHERE i.instance_id = ANY(p_instance_ids) + AND e.status = 'Running' + LIMIT 1; + + IF v_instance_id IS NOT NULL THEN + RAISE EXCEPTION 'Instance % is Running. Use force=true to delete.', v_instance_id; + END IF; + END IF; + + -- Step 2: Lock parent rows to prevent concurrent child creation + PERFORM 1 FROM SCHEMA.instances + WHERE instance_id = ANY(p_instance_ids) ++ ORDER BY instance_id + FOR UPDATE; + + -- Step 3: Check for orphans (children not in our delete list) + SELECT i.instance_id INTO v_orphan_id + FROM SCHEMA.instances i + WHERE i.parent_instance_id = ANY(p_instance_ids) + AND NOT (i.instance_id = ANY(p_instance_ids)) + LIMIT 1; + + IF v_orphan_id IS NOT NULL THEN + RAISE EXCEPTION 'Orphan detected: instance % has parent in delete list but is not included', v_orphan_id; + END IF; + + -- Step 4: Delete from all tables + DELETE FROM SCHEMA.history WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_events_deleted := v_count; + + DELETE FROM SCHEMA.executions WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_executions_deleted := v_count; + + DELETE FROM SCHEMA.orchestrator_queue WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_queue_deleted := v_count; + + DELETE FROM SCHEMA.worker_queue WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_queue_deleted := v_queue_deleted + v_count; + + DELETE FROM SCHEMA.instance_locks WHERE instance_id = ANY(p_instance_ids); + DELETE FROM SCHEMA.kv_delta WHERE instance_id = ANY(p_instance_ids); + DELETE FROM SCHEMA.kv_store WHERE instance_id = ANY(p_instance_ids); + + DELETE FROM SCHEMA.instances WHERE instance_id = ANY(p_instance_ids); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_instances_deleted := v_count; + + instances_deleted := v_instances_deleted; + executions_deleted := v_executions_deleted; + events_deleted := v_events_deleted; + queue_messages_deleted := v_queue_deleted; + RETURN NEXT; + END; + $function$ +\ No newline at end of file + +``` + ### `prune_executions_batch` — NEW ```sql CREATE OR REPLACE FUNCTION SCHEMA.prune_executions_batch(p_after_instance_id text, p_after_execution_id bigint, p_completed_before_ms bigint, p_limit integer) diff --git a/migrations/README.md b/migrations/README.md index d65533a..06aee87 100644 --- a/migrations/README.md +++ b/migrations/README.md @@ -131,6 +131,8 @@ Batches hold instance-row locks until their transaction ends and recheck execution eligibility after any lock wait. This serializes pruning with instance deletion/recreation and acknowledgement, protecting replacement instances and executions that become ineligible while the batch waits. +Pruning and atomic deletion acquire their instance locks in ascending instance-ID +order to avoid lock-order inversions during multi-instance operations. Use a maintenance connection with appropriate statement/lock timeouts. A failed call rolls back its entire batch. Applications that must progress past locked diff --git a/src/migrations.rs b/src/migrations.rs index f6577bd..f69ead9 100644 --- a/src/migrations.rs +++ b/src/migrations.rs @@ -8,7 +8,8 @@ use sqlx::PgPool; use std::collections::{HashMap, HashSet}; use std::sync::Arc; -// Touch this module when changing migrations so incremental builds re-embed them. Latest: 0028. +// Touch this module when changing migrations so incremental builds re-embed them. +// Latest change: 0028, ordered multi-instance locking. static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations"); const BASE_TABLES: &[&str] = &[ diff --git a/tests/deadlocks/pruning.rs b/tests/deadlocks/pruning.rs index 652e8c2..24d9769 100644 --- a/tests/deadlocks/pruning.rs +++ b/tests/deadlocks/pruning.rs @@ -8,24 +8,33 @@ use sqlx::{PgConnection, PgPool}; type BatchResult = (Option, Option, i64, i64, i64); -async fn seed_instance(schema: &str) -> PostgresProvider { +async fn seed_instances(schema: &str, instance_ids: &[&str]) -> PostgresProvider { let provider = PostgresProvider::new_with_schema(&database_url(), Some(schema)) .await .expect("failed to create provider"); + for instance_id in instance_ids { + sqlx::query(&format!( + "INSERT INTO {schema}.instances + (instance_id, orchestration_name, current_execution_id, created_at, updated_at) + VALUES ($1, 'test', 2, to_timestamp(0), to_timestamp(0))" + )) + .bind(*instance_id) + .execute(provider.pool()) + .await + .expect("failed to seed instance"); + } sqlx::Executor::execute( provider.pool(), format!( - "INSERT INTO {schema}.instances - (instance_id, orchestration_name, current_execution_id, created_at, updated_at) - VALUES ('pruning-race', 'test', 2, to_timestamp(0), to_timestamp(0)); - INSERT INTO {schema}.executions + "INSERT INTO {schema}.executions (instance_id, execution_id, status, started_at, completed_at) - VALUES ('pruning-race', 1, 'ContinuedAsNew', to_timestamp(0), to_timestamp(1)), - ('pruning-race', 2, 'Running', to_timestamp(1), NULL); + SELECT i.instance_id, n, CASE n WHEN 1 THEN 'ContinuedAsNew' ELSE 'Running' END, + to_timestamp(n - 1), CASE n WHEN 1 THEN to_timestamp(1) END + FROM {schema}.instances i CROSS JOIN generate_series(1, 2) n; INSERT INTO {schema}.history (instance_id, execution_id, event_id, event_type, event_data, created_at) - SELECT 'pruning-race', n, 1, 'Event', 'original', to_timestamp(0) - FROM generate_series(1, 2) n;" + SELECT instance_id, execution_id, 1, 'Event', 'original', to_timestamp(0) + FROM {schema}.executions;" ) .as_str(), ) @@ -66,7 +75,7 @@ async fn prune_batch(pool: PgPool, schema: String) -> Result(result) + }); + wait_for_call_to_wait(provider.pool(), &schema, "delete_instances_atomic", false).await; + + timed("pruning gate release", gate.commit()).await.unwrap(); + let prune_result = timed("batch pruning", prune).await.unwrap(); + let delete_result = timed("multi-instance deletion", delete).await.unwrap(); + assert_not_deadlock_victim("batch pruning", &prune_result); + assert_not_deadlock_victim("multi-instance deletion", &delete_result); + assert_eq!( + prune_result.expect("batch pruning must succeed"), + (Some("b".into()), Some(2), 4, 2, 2) + ); + assert_eq!( + delete_result.expect("multi-instance deletion must succeed"), + (2, 2, 2, 0) + ); + let mut connection = provider.pool().acquire().await.unwrap(); + assert_eq!( + durable_state(&mut connection, &schema).await, + serde_json::json!({"instances": null, "executions": null, "history": null}) + ); + }) + .await; +} From 7e5472726c5dbbabf78a0eb08032b1fe605c6760 Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Thu, 29 Oct 2026 16:50:38 +0000 Subject: [PATCH 05/10] Fix lock acquisition --- CHANGELOG.md | 5 +- migrations/0028_batched_execution_pruning.sql | 141 +++++++++++++++++ migrations/0028_diff.md | 146 ++++++++++++++++++ migrations/README.md | 11 +- src/migrations.rs | 2 +- tests/basic_tests.rs | 20 +++ tests/deadlocks/pruning.rs | 146 ++++++++++++++---- 7 files changed, 430 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0836cc..66ac64f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,10 +23,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Migration `0028` adds the `prune_executions_batch` SQL API. It scans at most 1,000 execution keys per call and returns a cursor even for protected or young rows, allowing maintenance to make bounded progress without changing retention. - Pruning serializes with instance deletion and execution updates, then rechecks - eligibility to protect replacement instances. + Both pruning APIs serialize with instance deletion and execution updates, then + check eligibility to protect replacement instances. Atomic deletion uses the same instance-ID lock order to prevent multi-instance deadlocks with pruning. + Public-schema cleanup also removes the batch-pruning function. ## [0.1.38] - 2026-10-26 diff --git a/migrations/0028_batched_execution_pruning.sql b/migrations/0028_batched_execution_pruning.sql index a8a8213..4d86c87 100644 --- a/migrations/0028_batched_execution_pruning.sql +++ b/migrations/0028_batched_execution_pruning.sql @@ -189,4 +189,145 @@ $fmt$, v_schema_name); END; $delete_atomic$ LANGUAGE plpgsql; $fmt$, v_schema_name); + + -- Whole-instance pruning must join the same instance-before-history lock + -- protocol. Its retention rules and deletion body are unchanged from 0019. + EXECUTE format($fmt$ + CREATE OR REPLACE FUNCTION %1$I.prune_executions( + p_instance_id TEXT, + p_keep_last INTEGER DEFAULT NULL, + p_completed_before_ms BIGINT DEFAULT NULL + ) + RETURNS TABLE( + instances_processed BIGINT, + executions_deleted BIGINT, + events_deleted BIGINT + ) AS $prune_exec$ + DECLARE + v_current_execution_id BIGINT; + v_executions_deleted BIGINT := 0; + v_events_deleted BIGINT := 0; + v_count BIGINT; + v_exec_ids_to_delete BIGINT[]; + v_exec_id BIGINT; + BEGIN + -- Get current execution ID (NEVER delete this) + SELECT i.current_execution_id INTO v_current_execution_id + FROM %1$I.instances i + WHERE i.instance_id = p_instance_id + FOR NO KEY UPDATE; + + IF NOT FOUND THEN + -- Instance doesn't exist - raise error + RAISE EXCEPTION 'Instance %% not found', p_instance_id; + END IF; + + -- Build list of executions to delete + -- CRITICAL: keep_last semantics - select top N executions INCLUDING current + -- None, Some(0), Some(1) are all equivalent (only current remains) + SELECT array_agg(e.execution_id) INTO v_exec_ids_to_delete + FROM %1$I.executions e + WHERE e.instance_id = p_instance_id + AND e.execution_id != v_current_execution_id -- Never delete current + AND e.status != 'Running' -- Never delete running + -- Apply completed_before filter if provided + AND (p_completed_before_ms IS NULL + OR e.completed_at < TO_TIMESTAMP(p_completed_before_ms / 1000.0)) + -- Apply keep_last filter: exclude top N by execution_id (including current) + AND (p_keep_last IS NULL + OR e.execution_id NOT IN ( + SELECT e2.execution_id + FROM %1$I.executions e2 + WHERE e2.instance_id = p_instance_id + ORDER BY e2.execution_id DESC + LIMIT p_keep_last + )); + + IF v_exec_ids_to_delete IS NULL OR array_length(v_exec_ids_to_delete, 1) IS NULL THEN + instances_processed := 1; + executions_deleted := 0; + events_deleted := 0; + RETURN NEXT; + RETURN; + END IF; + + FOREACH v_exec_id IN ARRAY v_exec_ids_to_delete LOOP + -- Delete history for this execution + DELETE FROM %1$I.history h + WHERE h.instance_id = p_instance_id + AND h.execution_id = v_exec_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + v_events_deleted := v_events_deleted + v_count; + + END LOOP; + + -- Delete executions + DELETE FROM %1$I.executions e + WHERE e.instance_id = p_instance_id + AND e.execution_id = ANY(v_exec_ids_to_delete); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_executions_deleted := v_count; + + instances_processed := 1; + executions_deleted := v_executions_deleted; + events_deleted := v_events_deleted; + RETURN NEXT; + END; + $prune_exec$ LANGUAGE plpgsql; +$fmt$, v_schema_name); + + EXECUTE format($fmt$ + CREATE OR REPLACE FUNCTION %1$I.cleanup_schema() + RETURNS VOID AS $cleanup$ + BEGIN + DROP TABLE IF EXISTS %1$I.sessions CASCADE; + DROP TABLE IF EXISTS %1$I.kv_delta CASCADE; + DROP TABLE IF EXISTS %1$I.kv_store CASCADE; + DROP TABLE IF EXISTS %1$I.instances CASCADE; + DROP TABLE IF EXISTS %1$I.executions CASCADE; + DROP TABLE IF EXISTS %1$I.history CASCADE; + DROP TABLE IF EXISTS %1$I.orchestrator_queue CASCADE; + DROP TABLE IF EXISTS %1$I.worker_queue CASCADE; + DROP TABLE IF EXISTS %1$I.instance_locks CASCADE; + DROP TABLE IF EXISTS %1$I._duroxide_migrations CASCADE; + + DROP FUNCTION IF EXISTS %1$I.cleanup_schema(); + DROP FUNCTION IF EXISTS %1$I.list_instances(); + DROP FUNCTION IF EXISTS %1$I.list_executions(TEXT); + DROP FUNCTION IF EXISTS %1$I.latest_execution_id(TEXT); + DROP FUNCTION IF EXISTS %1$I.list_instances_by_status(TEXT); + DROP FUNCTION IF EXISTS %1$I.get_instance_info(TEXT); + DROP FUNCTION IF EXISTS %1$I.get_execution_info(TEXT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.get_system_metrics(); + DROP FUNCTION IF EXISTS %1$I.get_queue_depths(BIGINT); + DROP FUNCTION IF EXISTS %1$I.enqueue_worker_work(TEXT, BIGINT, TEXT, BIGINT, BIGINT, TEXT); + DROP FUNCTION IF EXISTS %1$I.enqueue_worker_work(TEXT, BIGINT, TEXT, BIGINT, BIGINT, TEXT, TEXT); + DROP FUNCTION IF EXISTS %1$I.ack_worker(TEXT, TEXT, TEXT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.renew_work_item_lock(TEXT, BIGINT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.fetch_work_item(BIGINT, BIGINT, TEXT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.fetch_work_item(BIGINT, BIGINT, TEXT, BIGINT, TEXT[], TEXT); + DROP FUNCTION IF EXISTS %1$I.abandon_work_item(TEXT, BIGINT, BIGINT, BOOLEAN); + DROP FUNCTION IF EXISTS %1$I.enqueue_orchestrator_work(TEXT, TEXT, TIMESTAMPTZ, TEXT, TEXT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.fetch_orchestration_item(BIGINT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.fetch_orchestration_item(BIGINT, BIGINT, BIGINT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.ack_orchestration_item(TEXT, BIGINT, BIGINT, JSONB, JSONB, JSONB, JSONB, JSONB); + DROP FUNCTION IF EXISTS %1$I.abandon_orchestration_item(TEXT, BIGINT, BIGINT, BOOLEAN); + DROP FUNCTION IF EXISTS %1$I.renew_orchestration_item_lock(TEXT, BIGINT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.fetch_history(TEXT); + DROP FUNCTION IF EXISTS %1$I.fetch_history_with_execution(TEXT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.append_history(TEXT, BIGINT, JSONB); + DROP FUNCTION IF EXISTS %1$I.list_children(TEXT); + DROP FUNCTION IF EXISTS %1$I.get_parent_id(TEXT); + DROP FUNCTION IF EXISTS %1$I.delete_instances_atomic(TEXT[], BOOLEAN); + DROP FUNCTION IF EXISTS %1$I.prune_executions(TEXT, INTEGER, BIGINT); + DROP FUNCTION IF EXISTS %1$I.prune_executions_batch(TEXT, BIGINT, BIGINT, INTEGER); + DROP FUNCTION IF EXISTS %1$I.renew_session_lock(TEXT[], BIGINT, BIGINT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.cleanup_orphaned_sessions(BIGINT); + DROP FUNCTION IF EXISTS %1$I.get_custom_status(TEXT, BIGINT); + DROP FUNCTION IF EXISTS %1$I.get_kv_value(TEXT, TEXT); + DROP FUNCTION IF EXISTS %1$I.get_kv_all_values(TEXT); + DROP FUNCTION IF EXISTS %1$I.get_instance_stats(TEXT); + END; + $cleanup$ LANGUAGE plpgsql; +$fmt$, v_schema_name); END $$; diff --git a/migrations/0028_diff.md b/migrations/0028_diff.md index 362d1cc..00542df 100644 --- a/migrations/0028_diff.md +++ b/migrations/0028_diff.md @@ -14,6 +14,68 @@ None. The cursor and per-generation deletes use existing primary keys. ## Function Changes +### `cleanup_schema` — Body Modified (baseline: 0021) + +Full function with diff: +```diff + CREATE OR REPLACE FUNCTION SCHEMA.cleanup_schema() + RETURNS void + LANGUAGE plpgsql + AS $function$ + BEGIN + DROP TABLE IF EXISTS SCHEMA.sessions CASCADE; + DROP TABLE IF EXISTS SCHEMA.kv_delta CASCADE; + DROP TABLE IF EXISTS SCHEMA.kv_store CASCADE; + DROP TABLE IF EXISTS SCHEMA.instances CASCADE; + DROP TABLE IF EXISTS SCHEMA.executions CASCADE; + DROP TABLE IF EXISTS SCHEMA.history CASCADE; + DROP TABLE IF EXISTS SCHEMA.orchestrator_queue CASCADE; + DROP TABLE IF EXISTS SCHEMA.worker_queue CASCADE; + DROP TABLE IF EXISTS SCHEMA.instance_locks CASCADE; + DROP TABLE IF EXISTS SCHEMA._duroxide_migrations CASCADE; + + DROP FUNCTION IF EXISTS SCHEMA.cleanup_schema(); + DROP FUNCTION IF EXISTS SCHEMA.list_instances(); + DROP FUNCTION IF EXISTS SCHEMA.list_executions(TEXT); + DROP FUNCTION IF EXISTS SCHEMA.latest_execution_id(TEXT); + DROP FUNCTION IF EXISTS SCHEMA.list_instances_by_status(TEXT); + DROP FUNCTION IF EXISTS SCHEMA.get_instance_info(TEXT); + DROP FUNCTION IF EXISTS SCHEMA.get_execution_info(TEXT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.get_system_metrics(); + DROP FUNCTION IF EXISTS SCHEMA.get_queue_depths(BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.enqueue_worker_work(TEXT, BIGINT, TEXT, BIGINT, BIGINT, TEXT); + DROP FUNCTION IF EXISTS SCHEMA.enqueue_worker_work(TEXT, BIGINT, TEXT, BIGINT, BIGINT, TEXT, TEXT); + DROP FUNCTION IF EXISTS SCHEMA.ack_worker(TEXT, TEXT, TEXT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.renew_work_item_lock(TEXT, BIGINT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.fetch_work_item(BIGINT, BIGINT, TEXT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.fetch_work_item(BIGINT, BIGINT, TEXT, BIGINT, TEXT[], TEXT); + DROP FUNCTION IF EXISTS SCHEMA.abandon_work_item(TEXT, BIGINT, BIGINT, BOOLEAN); + DROP FUNCTION IF EXISTS SCHEMA.enqueue_orchestrator_work(TEXT, TEXT, TIMESTAMPTZ, TEXT, TEXT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.fetch_orchestration_item(BIGINT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.fetch_orchestration_item(BIGINT, BIGINT, BIGINT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.ack_orchestration_item(TEXT, BIGINT, BIGINT, JSONB, JSONB, JSONB, JSONB, JSONB); + DROP FUNCTION IF EXISTS SCHEMA.abandon_orchestration_item(TEXT, BIGINT, BIGINT, BOOLEAN); + DROP FUNCTION IF EXISTS SCHEMA.renew_orchestration_item_lock(TEXT, BIGINT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.fetch_history(TEXT); + DROP FUNCTION IF EXISTS SCHEMA.fetch_history_with_execution(TEXT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.append_history(TEXT, BIGINT, JSONB); + DROP FUNCTION IF EXISTS SCHEMA.list_children(TEXT); + DROP FUNCTION IF EXISTS SCHEMA.get_parent_id(TEXT); + DROP FUNCTION IF EXISTS SCHEMA.delete_instances_atomic(TEXT[], BOOLEAN); + DROP FUNCTION IF EXISTS SCHEMA.prune_executions(TEXT, INTEGER, BIGINT); ++ DROP FUNCTION IF EXISTS SCHEMA.prune_executions_batch(TEXT, BIGINT, BIGINT, INTEGER); + DROP FUNCTION IF EXISTS SCHEMA.renew_session_lock(TEXT[], BIGINT, BIGINT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.cleanup_orphaned_sessions(BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.get_custom_status(TEXT, BIGINT); + DROP FUNCTION IF EXISTS SCHEMA.get_kv_value(TEXT, TEXT); + DROP FUNCTION IF EXISTS SCHEMA.get_kv_all_values(TEXT); + DROP FUNCTION IF EXISTS SCHEMA.get_instance_stats(TEXT); + END; + $function$ +\ No newline at end of file + +``` + ### `delete_instances_atomic` — Body Modified (baseline: 0020) Full function with diff: @@ -109,6 +171,90 @@ Full function with diff: ``` +### `prune_executions` — Body Modified (baseline: 0019) + +Full function with diff: +```diff + CREATE OR REPLACE FUNCTION SCHEMA.prune_executions(p_instance_id text, p_keep_last integer DEFAULT NULL::integer, p_completed_before_ms bigint DEFAULT NULL::bigint) + RETURNS TABLE(instances_processed bigint, executions_deleted bigint, events_deleted bigint) + LANGUAGE plpgsql + AS $function$ + DECLARE + v_current_execution_id BIGINT; + v_executions_deleted BIGINT := 0; + v_events_deleted BIGINT := 0; + v_count BIGINT; + v_exec_ids_to_delete BIGINT[]; + v_exec_id BIGINT; + BEGIN + -- Get current execution ID (NEVER delete this) + SELECT i.current_execution_id INTO v_current_execution_id + FROM SCHEMA.instances i +- WHERE i.instance_id = p_instance_id; ++ WHERE i.instance_id = p_instance_id ++ FOR NO KEY UPDATE; + + IF NOT FOUND THEN + -- Instance doesn't exist - raise error + RAISE EXCEPTION 'Instance % not found', p_instance_id; + END IF; + + -- Build list of executions to delete + -- CRITICAL: keep_last semantics - select top N executions INCLUDING current + -- None, Some(0), Some(1) are all equivalent (only current remains) + SELECT array_agg(e.execution_id) INTO v_exec_ids_to_delete + FROM SCHEMA.executions e + WHERE e.instance_id = p_instance_id + AND e.execution_id != v_current_execution_id -- Never delete current + AND e.status != 'Running' -- Never delete running + -- Apply completed_before filter if provided + AND (p_completed_before_ms IS NULL + OR e.completed_at < TO_TIMESTAMP(p_completed_before_ms / 1000.0)) + -- Apply keep_last filter: exclude top N by execution_id (including current) + AND (p_keep_last IS NULL + OR e.execution_id NOT IN ( + SELECT e2.execution_id + FROM SCHEMA.executions e2 + WHERE e2.instance_id = p_instance_id + ORDER BY e2.execution_id DESC + LIMIT p_keep_last + )); + + IF v_exec_ids_to_delete IS NULL OR array_length(v_exec_ids_to_delete, 1) IS NULL THEN + instances_processed := 1; + executions_deleted := 0; + events_deleted := 0; + RETURN NEXT; + RETURN; + END IF; + + FOREACH v_exec_id IN ARRAY v_exec_ids_to_delete LOOP + -- Delete history for this execution + DELETE FROM SCHEMA.history h + WHERE h.instance_id = p_instance_id + AND h.execution_id = v_exec_id; + GET DIAGNOSTICS v_count = ROW_COUNT; + v_events_deleted := v_events_deleted + v_count; + + END LOOP; + + -- Delete executions + DELETE FROM SCHEMA.executions e + WHERE e.instance_id = p_instance_id + AND e.execution_id = ANY(v_exec_ids_to_delete); + GET DIAGNOSTICS v_count = ROW_COUNT; + v_executions_deleted := v_count; + + instances_processed := 1; + executions_deleted := v_executions_deleted; + events_deleted := v_events_deleted; + RETURN NEXT; + END; + $function$ +\ No newline at end of file + +``` + ### `prune_executions_batch` — NEW ```sql CREATE OR REPLACE FUNCTION SCHEMA.prune_executions_batch(p_after_instance_id text, p_after_execution_id bigint, p_completed_before_ms bigint, p_limit integer) diff --git a/migrations/README.md b/migrations/README.md index 06aee87..5190923 100644 --- a/migrations/README.md +++ b/migrations/README.md @@ -127,10 +127,10 @@ completion times are preserved, but still advance the cursor. Missing instance metadata is not permission to delete history. No instance, queue, lock, or KV records are removed. The number of history events per execution is not capped. -Batches hold instance-row locks until their transaction ends and recheck -execution eligibility after any lock wait. This serializes pruning with instance -deletion/recreation and acknowledgement, protecting replacement instances and -executions that become ineligible while the batch waits. +Both pruning APIs hold instance-row locks until their transactions end. They +check execution eligibility after acquiring the lock, serializing with instance +deletion/recreation and acknowledgement. This protects replacement instances and +executions that become ineligible while a call waits. Pruning and atomic deletion acquire their instance locks in ascending instance-ID order to avoid lock-order inversions during multi-instance operations. @@ -141,6 +141,9 @@ scan; a successful call's cursor remains authoritative if concurrent work change the page. Keep the original `prune_executions` API for callers that intentionally request a whole-instance historical cleanup. +Public-schema cleanup also removes the batch-pruning function, while leaving the +`public` schema itself intact. + ## Migration Execution Context - Migrations run inside transactions diff --git a/src/migrations.rs b/src/migrations.rs index f69ead9..2633553 100644 --- a/src/migrations.rs +++ b/src/migrations.rs @@ -9,7 +9,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; // Touch this module when changing migrations so incremental builds re-embed them. -// Latest change: 0028, ordered multi-instance locking. +// Latest change: 0028, shared pruning locks and complete cleanup. static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations"); const BASE_TABLES: &[&str] = &[ diff --git a/tests/basic_tests.rs b/tests/basic_tests.rs index d29658f..09c3c4f 100644 --- a/tests/basic_tests.rs +++ b/tests/basic_tests.rs @@ -80,6 +80,17 @@ async fn test_provider_creation_default_schema() { assert!(table_exists, "Tables should be created in public schema"); + let batch_pruner_exists_sql = "SELECT pg_catalog.to_regprocedure( + 'public.prune_executions_batch(text,bigint,bigint,integer)') IS NOT NULL"; + let batch_pruner_exists: bool = sqlx::query_scalar(batch_pruner_exists_sql) + .fetch_one(provider.pool()) + .await + .expect("Failed to check batch pruning function before cleanup"); + assert!( + batch_pruner_exists, + "Batch pruning function should be created" + ); + // Verify public schema exists before cleanup let public_schema_exists_before: bool = sqlx::query_scalar( "SELECT EXISTS(SELECT 1 FROM information_schema.schemata WHERE schema_name = 'public')", @@ -96,6 +107,15 @@ async fn test_provider_creation_default_schema() { // Cleanup: drop tables from public schema (but NOT the schema itself) provider.cleanup_schema().await.expect("Failed to cleanup"); + let batch_pruner_exists_after: bool = sqlx::query_scalar(batch_pruner_exists_sql) + .fetch_one(provider.pool()) + .await + .expect("Failed to check batch pruning function after cleanup"); + assert!( + !batch_pruner_exists_after, + "Public-schema cleanup must drop the batch pruning function" + ); + // Verify tables were dropped from public schema let table_exists_after: bool = sqlx::query_scalar( "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'instances')" diff --git a/tests/deadlocks/pruning.rs b/tests/deadlocks/pruning.rs index 24d9769..0ef0a08 100644 --- a/tests/deadlocks/pruning.rs +++ b/tests/deadlocks/pruning.rs @@ -8,7 +8,16 @@ use sqlx::{PgConnection, PgPool}; type BatchResult = (Option, Option, i64, i64, i64); -async fn seed_instances(schema: &str, instance_ids: &[&str]) -> PostgresProvider { +const SEQUENTIAL_SCANS_ONLY: &str = "SET LOCAL enable_seqscan = on; + SET LOCAL enable_indexscan = off; + SET LOCAL enable_indexonlyscan = off; + SET LOCAL enable_bitmapscan = off;"; + +async fn seed_instances( + schema: &str, + instance_ids: &[&str], + current_execution_id: i64, +) -> PostgresProvider { let provider = PostgresProvider::new_with_schema(&database_url(), Some(schema)) .await .expect("failed to create provider"); @@ -16,9 +25,10 @@ async fn seed_instances(schema: &str, instance_ids: &[&str]) -> PostgresProvider sqlx::query(&format!( "INSERT INTO {schema}.instances (instance_id, orchestration_name, current_execution_id, created_at, updated_at) - VALUES ($1, 'test', 2, to_timestamp(0), to_timestamp(0))" + VALUES ($1, 'test', $2, to_timestamp(0), to_timestamp(0))" )) .bind(*instance_id) + .bind(current_execution_id) .execute(provider.pool()) .await .expect("failed to seed instance"); @@ -28,9 +38,11 @@ async fn seed_instances(schema: &str, instance_ids: &[&str]) -> PostgresProvider format!( "INSERT INTO {schema}.executions (instance_id, execution_id, status, started_at, completed_at) - SELECT i.instance_id, n, CASE n WHEN 1 THEN 'ContinuedAsNew' ELSE 'Running' END, - to_timestamp(n - 1), CASE n WHEN 1 THEN to_timestamp(1) END - FROM {schema}.instances i CROSS JOIN generate_series(1, 2) n; + SELECT i.instance_id, n, + CASE WHEN n < i.current_execution_id THEN 'ContinuedAsNew' ELSE 'Running' END, + to_timestamp(n - 1), + CASE WHEN n < i.current_execution_id THEN to_timestamp(1) END + FROM {schema}.instances i CROSS JOIN generate_series(1, i.current_execution_id) n; INSERT INTO {schema}.history (instance_id, execution_id, event_id, event_type, event_data, created_at) SELECT instance_id, execution_id, 1, 'Event', 'original', to_timestamp(0) @@ -72,10 +84,36 @@ async fn prune_batch(pool: PgPool, schema: String) -> Result (i64, sqlx::Transaction<'static, sqlx::Postgres>) { + let ready_key = advisory_key(); + let gate_key = advisory_key(); + let mut gate = pool.begin().await.unwrap(); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(gate_key) + .execute(&mut *gate) + .await + .unwrap(); + install_pause_trigger_when( + pool, + schema, + "history", + "DELETE", + &format!("OLD.instance_id = $instance${instance}$instance$ AND OLD.execution_id = 1"), + ready_key, + gate_key, + ) + .await; + (ready_key, gate) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn batch_pruning_preserves_a_deleted_and_recreated_instance() { with_schema(|schema| async move { - let provider = seed_instances(&schema, &["pruning-race"]).await; + let provider = seed_instances(&schema, &["pruning-race"], 2).await; let mut replacement = provider.pool().begin().await.unwrap(); let deleted: (i64, i64, i64, i64) = sqlx::query_as(&format!( "SELECT * FROM {schema}.delete_instances_atomic(ARRAY['pruning-race'], TRUE)" @@ -127,7 +165,7 @@ async fn batch_pruning_preserves_a_deleted_and_recreated_instance() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn batch_pruning_rechecks_eligibility_after_an_instance_lock_wait() { with_schema(|schema| async move { - let provider = seed_instances(&schema, &["pruning-race"]).await; + let provider = seed_instances(&schema, &["pruning-race"], 2).await; let mut update = provider.pool().begin().await.unwrap(); sqlx::Executor::execute( &mut *update, @@ -167,25 +205,8 @@ async fn batch_pruning_rechecks_eligibility_after_an_instance_lock_wait() { async fn batch_pruning_and_multi_instance_deletion_lock_in_the_same_order() { with_schema(|schema| async move { // Heap order deliberately opposes the batch's instance-ID order. - let provider = seed_instances(&schema, &["b", "a"]).await; - let ready_key = advisory_key(); - let gate_key = advisory_key(); - let mut gate = provider.pool().begin().await.unwrap(); - sqlx::query("SELECT pg_advisory_xact_lock($1)") - .bind(gate_key) - .execute(&mut *gate) - .await - .unwrap(); - install_pause_trigger_when( - provider.pool(), - &schema, - "history", - "DELETE", - "OLD.instance_id = 'a' AND OLD.execution_id = 1", - ready_key, - gate_key, - ) - .await; + let provider = seed_instances(&schema, &["b", "a"], 2).await; + let (ready_key, gate) = pause_first_history_delete(provider.pool(), &schema, "a").await; let prune = tokio::spawn(prune_batch(provider.pool().clone(), schema.clone())); wait_for_advisory_holder(provider.pool(), ready_key).await; @@ -195,14 +216,7 @@ async fn batch_pruning_and_multi_instance_deletion_lock_in_the_same_order() { let delete = tokio::spawn(async move { let mut tx = delete_pool.begin().await?; // Without ORDER BY, this visits b before waiting for the batch's a lock. - sqlx::Executor::execute( - &mut *tx, - "SET LOCAL enable_seqscan = on; - SET LOCAL enable_indexscan = off; - SET LOCAL enable_indexonlyscan = off; - SET LOCAL enable_bitmapscan = off;", - ) - .await?; + sqlx::Executor::execute(&mut *tx, SEQUENTIAL_SCANS_ONLY).await?; let result: (i64, i64, i64, i64) = sqlx::query_as(&format!( "SELECT * FROM {delete_schema}.delete_instances_atomic(ARRAY['b', 'a'], TRUE)" )) @@ -234,3 +248,67 @@ async fn batch_pruning_and_multi_instance_deletion_lock_in_the_same_order() { }) .await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn batch_and_whole_instance_pruning_share_the_instance_lock() { + with_schema(|schema| async move { + let provider = seed_instances(&schema, &["pruning-race"], 3).await; + // Force the old whole-instance pruner to visit generation 2 before 1. + sqlx::Executor::execute( + provider.pool(), + format!( + "CREATE INDEX reverse_execution_order ON {schema}.executions (execution_id DESC); + CLUSTER {schema}.executions USING reverse_execution_order;" + ) + .as_str(), + ) + .await + .expect("failed to arrange reverse generation heap order"); + let mut connection = provider.pool().acquire().await.unwrap(); + let mut expected = durable_state(&mut connection, &schema).await; + for table in ["executions", "history"] { + expected[table] + .as_array_mut() + .expect("seeded durable rows must exist") + .retain(|row| row["execution_id"] == 3); + } + drop(connection); + + let (ready_key, gate) = + pause_first_history_delete(provider.pool(), &schema, "pruning-race").await; + let batch = tokio::spawn(prune_batch(provider.pool().clone(), schema.clone())); + wait_for_advisory_holder(provider.pool(), ready_key).await; + + let whole_pool = provider.pool().clone(); + let whole_schema = schema.clone(); + let whole = tokio::spawn(async move { + let mut tx = whole_pool.begin().await?; + sqlx::Executor::execute(&mut *tx, SEQUENTIAL_SCANS_ONLY).await?; + let result: (i64, i64, i64) = sqlx::query_as(&format!( + "SELECT * FROM {whole_schema}.prune_executions('pruning-race', NULL, 2000)" + )) + .fetch_one(&mut *tx) + .await?; + tx.commit().await?; + Ok::<_, sqlx::Error>(result) + }); + wait_for_call_to_wait(provider.pool(), &schema, "prune_executions", false).await; + + timed("pruning gate release", gate.commit()).await.unwrap(); + let batch_result = timed("batch pruning", batch).await.unwrap(); + let whole_result = timed("whole-instance pruning", whole).await.unwrap(); + assert_not_deadlock_victim("batch pruning", &batch_result); + assert_not_deadlock_victim("whole-instance pruning", &whole_result); + assert_eq!( + batch_result.expect("batch pruning must succeed"), + (Some("pruning-race".into()), Some(3), 3, 2, 2) + ); + assert_eq!( + whole_result.expect("whole-instance pruning must succeed"), + (1, 0, 0) + ); + let mut connection = provider.pool().acquire().await.unwrap(); + assert_eq!(durable_state(&mut connection, &schema).await, expected); + }) + .await; +} From 2ab6c359f7506cc8a0e75cb19a1a803a5d0c8e5e Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Fri, 30 Oct 2026 12:09:58 +0000 Subject: [PATCH 06/10] Avoid locking protected executions during batch pruning Precheck eligibility without changing scanned-key bounds or cursors, then retain the locked eligibility recheck. Exercise the hostile search_path with an eligible row and verify protected instances do not require locks. Ref: https://github.com/microsoft/duroxide-pg/pull/32 (32-S1, 32-S3) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- migrations/0028_batched_execution_pruning.sql | 10 ++- migrations/0028_diff.md | 10 ++- migrations/README.md | 6 +- src/migrations.rs | 2 +- tests/deadlocks/pruning.rs | 70 +++++++++++++++++++ tests/execution_pruning_tests.rs | 19 ++++- 6 files changed, 109 insertions(+), 8 deletions(-) diff --git a/migrations/0028_batched_execution_pruning.sql b/migrations/0028_batched_execution_pruning.sql index 4d86c87..4a0e68f 100644 --- a/migrations/0028_batched_execution_pruning.sql +++ b/migrations/0028_batched_execution_pruning.sql @@ -42,8 +42,12 @@ BEGIN executions_deleted := 0; events_deleted := 0; FOR v_execution IN - SELECT e.instance_id, e.execution_id + SELECT e.instance_id, e.execution_id, + e.execution_id < i.current_execution_id + AND e.status <> 'Running' + AND e.completed_at < to_timestamp(p_completed_before_ms / 1000.0) AS eligible FROM %1$I.executions e + LEFT JOIN %1$I.instances i ON i.instance_id = e.instance_id WHERE (e.instance_id, e.execution_id) > (p_after_instance_id, p_after_execution_id) ORDER BY e.instance_id, e.execution_id @@ -52,6 +56,10 @@ BEGIN last_instance_id := v_execution.instance_id; last_execution_id := v_execution.execution_id; executions_scanned := executions_scanned + 1; + IF v_execution.eligible IS NOT TRUE THEN + CONTINUE; + END IF; + -- Lock before touching history, as deletion does. The page may -- describe an earlier lifetime of the same instance/execution key. SELECT i.current_execution_id INTO v_current_execution_id diff --git a/migrations/0028_diff.md b/migrations/0028_diff.md index 00542df..fd57fcf 100644 --- a/migrations/0028_diff.md +++ b/migrations/0028_diff.md @@ -279,8 +279,12 @@ AS $function$ executions_deleted := 0; events_deleted := 0; FOR v_execution IN - SELECT e.instance_id, e.execution_id + SELECT e.instance_id, e.execution_id, + e.execution_id < i.current_execution_id + AND e.status <> 'Running' + AND e.completed_at < to_timestamp(p_completed_before_ms / 1000.0) AS eligible FROM SCHEMA.executions e + LEFT JOIN SCHEMA.instances i ON i.instance_id = e.instance_id WHERE (e.instance_id, e.execution_id) > (p_after_instance_id, p_after_execution_id) ORDER BY e.instance_id, e.execution_id @@ -289,6 +293,10 @@ AS $function$ last_instance_id := v_execution.instance_id; last_execution_id := v_execution.execution_id; executions_scanned := executions_scanned + 1; + IF v_execution.eligible IS NOT TRUE THEN + CONTINUE; + END IF; + -- Lock before touching history, as deletion does. The page may -- describe an earlier lifetime of the same instance/execution key. SELECT i.current_execution_id INTO v_current_execution_id diff --git a/migrations/README.md b/migrations/README.md index 5190923..a58f243 100644 --- a/migrations/README.md +++ b/migrations/README.md @@ -127,8 +127,10 @@ completion times are preserved, but still advance the cursor. Missing instance metadata is not permission to delete history. No instance, queue, lock, or KV records are removed. The number of history events per execution is not capped. -Both pruning APIs hold instance-row locks until their transactions end. They -check execution eligibility after acquiring the lock, serializing with instance +Batched pruning checks eligibility without locking first, so an instance with no +deletion candidates is not locked. Protected rows still count toward the page. +Both pruning APIs hold acquired instance-row locks until their transactions end. +They check execution eligibility after acquiring the lock, serializing with instance deletion/recreation and acknowledgement. This protects replacement instances and executions that become ineligible while a call waits. Pruning and atomic deletion acquire their instance locks in ascending instance-ID diff --git a/src/migrations.rs b/src/migrations.rs index 2633553..da4538a 100644 --- a/src/migrations.rs +++ b/src/migrations.rs @@ -9,7 +9,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; // Touch this module when changing migrations so incremental builds re-embed them. -// Latest change: 0028, shared pruning locks and complete cleanup. +// Latest change: 0028, precheck batch eligibility before acquiring instance locks. static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations"); const BASE_TABLES: &[&str] = &[ diff --git a/tests/deadlocks/pruning.rs b/tests/deadlocks/pruning.rs index 0ef0a08..83e4433 100644 --- a/tests/deadlocks/pruning.rs +++ b/tests/deadlocks/pruning.rs @@ -110,6 +110,76 @@ async fn pause_first_history_delete( (ready_key, gate) } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn batch_pruning_does_not_lock_ineligible_instances() { + with_schema(|schema| async move { + let provider = seed_instances( + &schema, + &[ + "a-current", + "b-future", + "c-running", + "d-null", + "e-cutoff", + "f-young", + "z-eligible", + ], + 2, + ) + .await; + sqlx::raw_sql(&format!( + "UPDATE {schema}.instances SET current_execution_id=1 WHERE instance_id='a-current'; + UPDATE {schema}.instances SET current_execution_id=0 WHERE instance_id='b-future'; + UPDATE {schema}.executions SET status='Running' WHERE instance_id='c-running'; + UPDATE {schema}.executions SET completed_at=NULL WHERE instance_id='d-null'; + UPDATE {schema}.executions SET completed_at=to_timestamp(2) WHERE instance_id='e-cutoff'; + UPDATE {schema}.executions SET completed_at=to_timestamp(3) WHERE instance_id='f-young';" + )) + .execute(provider.pool()) + .await + .unwrap(); + let mut locked = provider.pool().begin().await.unwrap(); + let mut expected = durable_state(&mut locked, &schema).await; + for table in ["executions", "history"] { + expected[table] + .as_array_mut() + .expect("seeded durable rows must exist") + .retain(|row| row["instance_id"] != "z-eligible" || row["execution_id"] != 1); + } + sqlx::query(&format!( + "SELECT 1 FROM {schema}.instances WHERE instance_id <> 'z-eligible' + ORDER BY instance_id FOR NO KEY UPDATE" + )) + .execute(&mut *locked) + .await + .unwrap(); + + let mut prune = provider.pool().begin().await.unwrap(); + sqlx::query("SET LOCAL lock_timeout = '1s'") + .execute(&mut *prune) + .await + .unwrap(); + let result: BatchResult = timed( + "pruning past locked ineligible instances", + sqlx::query_as(&format!( + "SELECT * FROM {schema}.prune_executions_batch('', 0, 2000, 1000)" + )) + .fetch_one(&mut *prune), + ) + .await + .expect("protected instances must not require row locks"); + assert_eq!(result, (Some("z-eligible".into()), Some(2), 14, 1, 1)); + prune.commit().await.unwrap(); + assert_eq!( + durable_state(&mut locked, &schema).await, + expected, + "only the eligible historical execution and its history may change" + ); + locked.rollback().await.unwrap(); + }) + .await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn batch_pruning_preserves_a_deleted_and_recreated_instance() { with_schema(|schema| async move { diff --git a/tests/execution_pruning_tests.rs b/tests/execution_pruning_tests.rs index 172ab4b..234df2e 100644 --- a/tests/execution_pruning_tests.rs +++ b/tests/execution_pruning_tests.rs @@ -49,15 +49,28 @@ async fn batch_pruning_bounds_scanned_keys_and_rolls_back_atomically() { let sql = format!("SELECT * FROM {schema}.prune_executions_batch($1,$2,$3,$4)"); let mut hostile = provider.pool().begin().await.unwrap(); sqlx::raw_sql(&format!( - "CREATE FUNCTION {schema}.to_timestamp(double precision) RETURNS timestamptz + "UPDATE {schema}.instances SET current_execution_id=2 WHERE instance_id='a0001'; + INSERT INTO {schema}.executions(instance_id,execution_id,status,started_at) + VALUES ('a0001',2,'Running',to_timestamp(1)); + CREATE FUNCTION {schema}.to_timestamp(double precision) RETURNS timestamptz LANGUAGE plpgsql AS $fn$ BEGIN RAISE EXCEPTION 'pruning function trap'; END $fn$; SET LOCAL search_path={schema},pg_catalog; CREATE TEMP TABLE type_anchor(id int); - CREATE DOMAIN pg_temp.text AS pg_catalog.text CHECK (false);" + CREATE DOMAIN pg_temp.text AS pg_catalog.text CHECK (false); + SAVEPOINT trap_probe;" )) .execute(&mut *hostile) .await .unwrap(); + let error = sqlx::query("SELECT to_timestamp(0::double precision)") + .execute(&mut *hostile) + .await + .unwrap_err(); + assert!(error.to_string().contains("pruning function trap")); + sqlx::query("ROLLBACK TO SAVEPOINT trap_probe") + .execute(&mut *hostile) + .await + .unwrap(); let first: BatchResult = sqlx::query_as(&sql) .bind("") .bind(0i64) @@ -66,7 +79,7 @@ async fn batch_pruning_bounds_scanned_keys_and_rolls_back_atomically() { .fetch_one(&mut *hostile) .await .unwrap(); - assert_eq!(first, (Some("a1000".into()), Some(1), 1000, 0, 0)); + assert_eq!(first, (Some("a0999".into()), Some(1), 1000, 1, 1)); hostile.rollback().await.unwrap(); sqlx::raw_sql(&format!( From e7a6c4bce0d655bd4c4ca3d272068b2aed4c344f Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Fri, 30 Oct 2026 12:15:14 +0000 Subject: [PATCH 07/10] Report malformed history keys during continue-as-new backfill Keep the backfill set-based on success and preserve SQLSTATE while adding the failing history key on JSONB decode errors. Verify atomic rollback, valid upgrades, and a schema built entirely from the pre-0027 migration prefix. Ref: https://github.com/microsoft/duroxide-pg/pull/32 (backfill diagnostics and upgrade-fixture review notes) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../0027_continue_as_new_completed_at.sql | 57 +++-- migrations/0027_diff.md | 3 + migrations/README.md | 4 + src/migrations.rs | 2 +- tests/regression_tests.rs | 221 ++++++++++++++++-- 5 files changed, 252 insertions(+), 35 deletions(-) diff --git a/migrations/0027_continue_as_new_completed_at.sql b/migrations/0027_continue_as_new_completed_at.sql index 6af41ca..609e20e 100644 --- a/migrations/0027_continue_as_new_completed_at.sql +++ b/migrations/0027_continue_as_new_completed_at.sql @@ -8,6 +8,7 @@ DO $$ DECLARE v_schema_name TEXT := current_schema(); v_unresolved BIGINT; + v_history RECORD; BEGIN EXECUTE format($fmt$ CREATE OR REPLACE FUNCTION %1$I.ack_orchestration_item( @@ -311,24 +312,46 @@ $fmt$, v_schema_name); -- History.created_at used the same provider clock as the acknowledgement. -- event_type can contain "Event", so inspect the serialized discriminator. - EXECUTE format($fmt$ - WITH completion_times AS ( - SELECT e.instance_id, e.execution_id, terminal.created_at - FROM %1$I.executions e - CROSS JOIN LATERAL ( - SELECT h.created_at FROM %1$I.history h - WHERE h.instance_id = e.instance_id AND h.execution_id = e.execution_id - AND h.event_data::jsonb->>'type' = 'OrchestrationContinuedAsNew' - ORDER BY h.event_id DESC LIMIT 1 - ) terminal - WHERE e.status = 'ContinuedAsNew' AND e.completed_at IS NULL - ) - UPDATE %1$I.executions e - SET completed_at = c.created_at - FROM completion_times c - WHERE e.instance_id = c.instance_id AND e.execution_id = c.execution_id - AND e.status = 'ContinuedAsNew' AND e.completed_at IS NULL + BEGIN + EXECUTE format($fmt$ + WITH completion_times AS ( + SELECT e.instance_id, e.execution_id, terminal.created_at + FROM %1$I.executions e + CROSS JOIN LATERAL ( + SELECT h.created_at FROM %1$I.history h + WHERE h.instance_id = e.instance_id AND h.execution_id = e.execution_id + AND h.event_data::jsonb->>'type' = 'OrchestrationContinuedAsNew' + ORDER BY h.event_id DESC LIMIT 1 + ) terminal + WHERE e.status = 'ContinuedAsNew' AND e.completed_at IS NULL + ) + UPDATE %1$I.executions e + SET completed_at = c.created_at + FROM completion_times c + WHERE e.instance_id = c.instance_id AND e.execution_id = c.execution_id + AND e.status = 'ContinuedAsNew' AND e.completed_at IS NULL $fmt$, v_schema_name); + EXCEPTION WHEN data_exception THEN + -- Only rescan on failure, keeping successful backfills set-based. + FOR v_history IN EXECUTE format($fmt$ + SELECT h.instance_id, h.execution_id, h.event_id, h.event_data + FROM %1$I.history h + JOIN %1$I.executions e USING (instance_id, execution_id) + WHERE e.status = 'ContinuedAsNew' AND e.completed_at IS NULL + ORDER BY h.instance_id, h.execution_id, h.event_id DESC +$fmt$, v_schema_name) + LOOP + BEGIN + PERFORM v_history.event_data::jsonb; + EXCEPTION WHEN data_exception THEN + RAISE EXCEPTION 'Migration 0027: invalid history event_data in schema % (instance_id=%, execution_id=%, event_id=%): %', + v_schema_name, v_history.instance_id, v_history.execution_id, + v_history.event_id, SQLERRM + USING ERRCODE = SQLSTATE; + END; + END LOOP; + RAISE; + END; EXECUTE format( 'SELECT count(*) FROM %I.executions WHERE status = ''ContinuedAsNew'' AND completed_at IS NULL', diff --git a/migrations/0027_diff.md b/migrations/0027_diff.md index b77a05f..b8ad8a0 100644 --- a/migrations/0027_diff.md +++ b/migrations/0027_diff.md @@ -9,6 +9,9 @@ Each changed function is shown **in full** with `+`/`-` markers on changed lines No structural changes. The migration backfills NULL completion timestamps for continued executions from terminal history events. Unrecoverable rows remain NULL and produce a warning; no executions or history are deleted. +History JSONB decode failures abort the migration with the original SQLSTATE and +the schema, instance, execution, and event key. The diagnostic scan runs only on +failure; successful backfills remain set-based. ## New Indexes diff --git a/migrations/README.md b/migrations/README.md index a58f243..eaa6e8d 100644 --- a/migrations/README.md +++ b/migrations/README.md @@ -99,6 +99,10 @@ execution's last `OrchestrationContinuedAsNew` history event. This uses the same provider clock as acknowledgement, not the execution's start time or upgrade time. Existing non-NULL timestamps and other execution statuses are unchanged. +If a history payload cannot be decoded as JSONB, the migration aborts and reports +its schema, instance, execution, and event key. No timestamp changes or function +replacements from migration `0027` are committed on failure. + If no terminal event is available, the timestamp stays NULL and the migration warns with the affected row count. These rows remain ineligible for age-based pruning; inspect their history before choosing an explicit count-based policy. diff --git a/src/migrations.rs b/src/migrations.rs index da4538a..fdddc04 100644 --- a/src/migrations.rs +++ b/src/migrations.rs @@ -9,7 +9,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; // Touch this module when changing migrations so incremental builds re-embed them. -// Latest change: 0028, precheck batch eligibility before acquiring instance locks. +// Latest change: 0027/0028, contextual backfill errors and candidate-only pruning locks. static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations"); const BASE_TABLES: &[&str] = &[ diff --git a/tests/regression_tests.rs b/tests/regression_tests.rs index da11246..0baf94b 100644 --- a/tests/regression_tests.rs +++ b/tests/regression_tests.rs @@ -42,6 +42,205 @@ async fn cleanup_schema(schema_name: &str) { .expect("Failed to drop schema"); } +async fn create_pre_0027_schema(pool: &sqlx::PgPool, schema: &str) { + static MIGRATIONS: include_dir::Dir = + include_dir::include_dir!("$CARGO_MANIFEST_DIR/migrations"); + let mut files: Vec<_> = MIGRATIONS + .files() + .filter(|file| file.path().extension().and_then(|ext| ext.to_str()) == Some("sql")) + .collect(); + files.sort_by_key(|file| file.path()); + + let mut tx = pool.begin().await.unwrap(); + sqlx::raw_sql(&format!( + "CREATE SCHEMA {schema}; + SET LOCAL search_path TO {schema}, pg_temp; + CREATE TABLE _duroxide_migrations ( + version BIGINT PRIMARY KEY, + name TEXT NOT NULL, + applied_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP + );" + )) + .execute(&mut *tx) + .await + .unwrap(); + for file in files { + let name = file.path().file_name().unwrap().to_str().unwrap(); + let version: i64 = name.split_once('_').unwrap().0.parse().unwrap(); + if version >= 27 { + break; + } + sqlx::raw_sql(file.contents_utf8().unwrap()) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("INSERT INTO _duroxide_migrations (version, name) VALUES ($1, $2)") + .bind(version) + .bind(name) + .execute(&mut *tx) + .await + .unwrap(); + } + let last_version: i64 = sqlx::query_scalar("SELECT max(version) FROM _duroxide_migrations") + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(last_version, 26); + let batch_function: Option = sqlx::query_scalar( + "SELECT to_regprocedure('prune_executions_batch(text,bigint,bigint,integer)')::text", + ) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert!(batch_function.is_none(), "no post-0026 objects may survive"); + tx.commit().await.unwrap(); +} + +#[tokio::test] +async fn test_continue_as_new_backfill_reports_malformed_history_key() { + let schema = unique_schema_name(); + let database_url = get_database_url(); + let pool = PgPoolOptions::new() + .max_connections(2) + .connect(&database_url) + .await + .unwrap(); + create_pre_0027_schema(&pool, &schema).await; + sqlx::raw_sql(&format!( + "INSERT INTO {schema}.instances + (instance_id, orchestration_name, current_execution_id, created_at, updated_at) + VALUES ('damaged-history', 'test', 3, to_timestamp(0), to_timestamp(0)); + INSERT INTO {schema}.executions + (instance_id, execution_id, status, started_at) + SELECT 'damaged-history', n, + CASE WHEN n < 3 THEN 'ContinuedAsNew' ELSE 'Running' END, to_timestamp(0) + FROM generate_series(1, 3) n; + INSERT INTO {schema}.history + (instance_id, execution_id, event_id, event_type, event_data, created_at) + SELECT 'damaged-history', n, 7, 'Event', + '{{\"type\":\"OrchestrationContinuedAsNew\",\"input\":\"next\"}}', to_timestamp(n) + FROM generate_series(1, 2) n;" + )) + .execute(&pool) + .await + .unwrap(); + let snapshot_sql = format!( + "SELECT jsonb_build_object( + 'ledger', (SELECT jsonb_agg(m ORDER BY m.version) FROM {schema}._duroxide_migrations m), + 'functions', (SELECT jsonb_agg(pg_get_functiondef(p.oid) ORDER BY p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='{schema}'), + 'instances', (SELECT jsonb_agg(i ORDER BY i.instance_id) FROM {schema}.instances i), + 'executions', (SELECT jsonb_agg(e ORDER BY e.instance_id, e.execution_id) + FROM {schema}.executions e), + 'history', (SELECT jsonb_agg(h ORDER BY h.instance_id, h.execution_id, h.event_id) + FROM {schema}.history h))" + ); + for (payload, code) in [ + ("not json", "22P02"), + ( + r#"{"type":"OrchestrationContinuedAsNew","input":"\u0000"}"#, + "22P05", + ), + ( + r#"{"type":"OrchestrationContinuedAsNew","value":1e1000000}"#, + "22003", + ), + ] { + sqlx::query(&format!( + "UPDATE {schema}.history SET event_data=$1 + WHERE instance_id='damaged-history' AND execution_id=2 AND event_id=7" + )) + .bind(payload) + .execute(&pool) + .await + .unwrap(); + let before: serde_json::Value = sqlx::query_scalar(&snapshot_sql) + .fetch_one(&pool) + .await + .unwrap(); + let mut tx = pool.begin().await.unwrap(); + sqlx::query(&format!("SET LOCAL search_path TO {schema}, pg_temp")) + .execute(&mut *tx) + .await + .unwrap(); + let error = sqlx::raw_sql(include_str!( + "../migrations/0027_continue_as_new_completed_at.sql" + )) + .execute(&mut *tx) + .await + .unwrap_err(); + tx.rollback().await.unwrap(); + let startup_error = PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .err() + .expect("startup must reject malformed durable history"); + let after: serde_json::Value = sqlx::query_scalar(&snapshot_sql) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + after, before, + "a rejected backfill must not change the ledger, functions, or durable state" + ); + let database_error = error.as_database_error().unwrap(); + assert_eq!(database_error.code().as_deref(), Some(code)); + for context in [ + schema.as_str(), + "damaged-history", + "execution_id=2", + "event_id=7", + ] { + assert!( + database_error.message().contains(context), + "missing {context:?} in backfill error: {error}" + ); + assert!( + startup_error.to_string().contains(context), + "startup must preserve the backfill error context" + ); + } + } + + sqlx::query(&format!( + "UPDATE {schema}.history + SET event_data='{{\"type\":\"OrchestrationContinuedAsNew\",\"input\":\"next\"}}' + WHERE instance_id='damaged-history' AND execution_id=2 AND event_id=7" + )) + .execute(&pool) + .await + .unwrap(); + let before: serde_json::Value = sqlx::query_scalar(&snapshot_sql) + .fetch_one(&pool) + .await + .unwrap(); + let provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .expect("valid history must allow the upgrade"); + let timestamps: Vec> = sqlx::query_scalar(&format!( + "SELECT (extract(epoch FROM completed_at)*1000)::bigint FROM {schema}.executions + ORDER BY execution_id" + )) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(timestamps, [Some(1_000), Some(2_000), None]); + let after: serde_json::Value = sqlx::query_scalar(&snapshot_sql) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(after["history"], before["history"]); + assert_eq!(after["instances"], before["instances"]); + let old_ledger = before["ledger"].as_array().unwrap(); + let new_ledger = after["ledger"].as_array().unwrap(); + assert_eq!(&new_ledger[..old_ledger.len()], old_ledger); + assert_eq!(new_ledger[old_ledger.len()]["version"], 27); + assert_eq!(new_ledger[old_ledger.len() + 1]["version"], 28); + cleanup_schema(&schema).await; + provider.pool().close().await; + pool.close().await; +} + #[tokio::test] async fn test_age_pruning_continue_as_new() { verify_age_pruning(false).await; @@ -61,25 +260,13 @@ async fn verify_age_pruning(upgrade: bool) { .unwrap(), ); if upgrade { - // Generate real histories using the shipped acknowledgement function. - let mut tx = store.pool().begin().await.unwrap(); - sqlx::query(&format!("SET LOCAL search_path TO {schema}, pg_temp")) - .execute(&mut *tx) + // Constructors migrate eagerly. Rebuild the disposable schema from the + // old prefix before generating history, rather than only downgrading ack. + sqlx::query(&format!("DROP SCHEMA {schema} CASCADE")) + .execute(store.pool()) .await .unwrap(); - sqlx::raw_sql(include_str!( - "../migrations/0026_serialize_orchestration_lock_mutations.sql" - )) - .execute(&mut *tx) - .await - .unwrap(); - sqlx::query(&format!( - "DELETE FROM {schema}._duroxide_migrations WHERE version >= 27" - )) - .execute(&mut *tx) - .await - .unwrap(); - tx.commit().await.unwrap(); + create_pre_0027_schema(store.pool(), &schema).await; } let orchestrations = OrchestrationRegistry::builder() From f20f7ef13aceed876e6b31dcdd2a45847af50a3f Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Fri, 30 Oct 2026 12:17:37 +0000 Subject: [PATCH 08/10] Document fully drained upgrades and timestamp repair Require draining all provider callers, pause retention during upgrades, and describe the one-time deletion wave and backfill/WAL cost. Document an explicit timestamp-only repair after draining, preserve the migration ledger, and classify existing-procedure fixes under Fixed. Ref: https://github.com/microsoft/duroxide-pg/pull/32 (32-M1, 32-S2, changelog review note) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 28 ++++++++++++--- migrations/README.md | 81 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 100 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 66ac64f..2e66268 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,18 +17,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 missing timestamps from terminal history events without changing current execution protection. Rows without a recoverable terminal event remain NULL and produce a migration warning. +- Both pruning APIs serialize with instance deletion and execution updates, then + recheck eligibility to protect replacement instances. Atomic deletion uses the + same instance-ID lock order to prevent multi-instance deadlocks with pruning + (migration `0028`). ### Added - Migration `0028` adds the `prune_executions_batch` SQL API. It scans at most 1,000 execution keys per call and returns a cursor even for protected or young rows, allowing maintenance to make bounded progress without changing retention. - Both pruning APIs serialize with instance deletion and execution updates, then - check eligibility to protect replacement instances. - Atomic deletion uses the same instance-ID lock order to prevent multi-instance - deadlocks with pruning. + It locks only instances with deletion candidates. Public-schema cleanup also removes the batch-pruning function. +### Upgrading + +- **Migrations `0027` and `0028` require a fully drained upgrade.** Pause delete + and prune jobs, then stop and drain every process that uses the provider: + workers, clients, retention and maintenance jobs, and direct SQL callers. + Wait for in-flight calls and transactions to finish. Apply the migrations with + provider traffic stopped, then restart only new binaries and updated SQL + callers. Stopping only workers is insufficient: old age-based deletion code + can delete pending continuations after their completion timestamps are filled. +- Expect a one-time wave of age-based deletions of old continue-as-new + generations when retention resumes. Review retention cutoffs before restarting + delete and prune jobs. Backfill time and WAL volume grow with the number of + continue-as-new rows to repair; budget the maintenance window accordingly. +- If an upgrade was not fully drained, old acknowledgements can leave missing + timestamps after the backfill. Stop and drain all callers before following the + [explicit repair procedure](migrations/README.md#repairing-missing-continued-execution-timestamps). + Re-running the backfill while old calls remain in flight does not close that + race. + ## [0.1.38] - 2026-10-26 ### Fixed diff --git a/migrations/README.md b/migrations/README.md index eaa6e8d..eb1e4b1 100644 --- a/migrations/README.md +++ b/migrations/README.md @@ -110,10 +110,79 @@ The migration itself deletes no executions or history. Once timestamps are recovered, subsequent age-based pruning can remove generations older than the configured cutoff, while still protecting the current and running executions. -Stop worker runtimes before upgrading and resume them after migrations complete, -so acknowledgements using the old function cannot race the one-time backfill. -The backfill can take time on a large history store. The migration is idempotent; -reapplying it does not change already populated timestamps. +#### Upgrading safely + +Migrations `0027` and `0028` require a fully drained upgrade, not a rolling +upgrade with old and new provider binaries running together: + +1. Pause all delete and prune jobs. +2. Stop and drain **every process that uses the provider**: workers, clients, + retention and maintenance jobs, and direct SQL callers. Wait for in-flight + calls and transactions to finish. +3. Apply the migrations with provider traffic still stopped, then restart only + new binaries containing these fixes and updated direct SQL callers. +4. Review retention cutoffs before resuming delete and prune jobs. Expect a + one-time wave of age-based deletions of old continue-as-new generations whose + completion timestamps have now been recovered. + +Stopping only workers is insufficient. An old client's age-based deletion +selector can select a pending continuation after its completion timestamp has +been filled, deleting the instance and its queued continuation. + +Backfill time and WAL volume grow with the number of continue-as-new rows to +repair. Large histories can further increase backfill time. Allow for this work +in the maintenance window and WAL storage budget. + +#### Repairing missing continued-execution timestamps + +If an upgrade was not fully drained, an acknowledgement already executing the +old function can write a NULL `completed_at` after the backfill. These rows remain +ineligible for age-based pruning. **Draining all callers is the fence**: +re-running the backfill while old calls remain in flight does not close the race. + +First pause deletion and pruning, stop and drain all callers as above, and ensure +the migrations have completed. With provider traffic still stopped, replace +`your_provider_schema` below and run this transaction. It fills only missing +`ContinuedAsNew` timestamps using the last terminal history event's original +`created_at`; existing timestamps and other statuses are unchanged. It neither +replaces functions nor changes the migration ledger. Do not delete migration +tracking rows or re-run whole migrations to perform this repair. + +```sql +BEGIN; +SET LOCAL search_path TO your_provider_schema, pg_temp; + +WITH completion_times AS ( + SELECT e.instance_id, e.execution_id, terminal.created_at + FROM executions e + CROSS JOIN LATERAL ( + SELECT h.created_at + FROM history h + WHERE h.instance_id = e.instance_id + AND h.execution_id = e.execution_id + AND h.event_data::jsonb->>'type' = 'OrchestrationContinuedAsNew' + ORDER BY h.event_id DESC + LIMIT 1 + ) terminal + WHERE e.status = 'ContinuedAsNew' AND e.completed_at IS NULL +) +UPDATE executions e +SET completed_at = c.created_at +FROM completion_times c +WHERE e.instance_id = c.instance_id AND e.execution_id = c.execution_id + AND e.status = 'ContinuedAsNew' AND e.completed_at IS NULL; + +SELECT instance_id, execution_id +FROM executions +WHERE status = 'ContinuedAsNew' AND completed_at IS NULL +ORDER BY instance_id, execution_id; +COMMIT; +``` + +Rows returned by the final query have no recoverable terminal timestamp; inspect +their history rather than substituting the current time. Invalid history JSONB +aborts the transaction instead of being skipped. After repair, restart only new +binaries and updated SQL callers, then resume retention with reviewed cutoffs. ### Batched execution pruning (0028) @@ -167,7 +236,9 @@ Public-schema cleanup also removes the batch-pruning function, while leaving the ### Migration already applied - Check the `_duroxide_migrations` table in your schema -- If you need to re-run a migration, manually delete its entry from the tracking table (use with caution!) +- Keep applied migration records intact. Use a documented data repair, such as + the continued-execution timestamp repair above, or a new migration rather than + deleting ledger rows to force old migrations to run again. ### Schema conflicts - Each schema maintains its own migration history From 79870890d1a4a14eb840ec1d31d0b6dff0716c0a Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Fri, 30 Oct 2026 16:12:31 +0000 Subject: [PATCH 09/10] Clarify which process applies migrations during upgrades Start one new ApplyAll process first and wait for provider initialization to complete before restarting the remaining upgraded callers. Keep migrations numbered 0027/0028 pending merge-order coordination. Ref: https://github.com/microsoft/duroxide-pg/pull/32 (upgrade-startup review nit) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 8 +++++--- migrations/README.md | 9 ++++++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e66268..678b8b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,9 +35,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Migrations `0027` and `0028` require a fully drained upgrade.** Pause delete and prune jobs, then stop and drain every process that uses the provider: workers, clients, retention and maintenance jobs, and direct SQL callers. - Wait for in-flight calls and transactions to finish. Apply the migrations with - provider traffic stopped, then restart only new binaries and updated SQL - callers. Stopping only workers is insufficient: old age-based deletion code + Wait for in-flight calls and transactions to finish. Start one process using + the new binary with `MigrationPolicy::ApplyAll` first; provider initialization + applies the migrations. Keep provider traffic stopped until initialization + succeeds, then restart the remaining new binaries and updated SQL callers. + Stopping only workers is insufficient: old age-based deletion code can delete pending continuations after their completion timestamps are filled. - Expect a one-time wave of age-based deletions of old continue-as-new generations when retention resumes. Review retention cutoffs before restarting diff --git a/migrations/README.md b/migrations/README.md index eb1e4b1..052de64 100644 --- a/migrations/README.md +++ b/migrations/README.md @@ -119,9 +119,12 @@ upgrade with old and new provider binaries running together: 2. Stop and drain **every process that uses the provider**: workers, clients, retention and maintenance jobs, and direct SQL callers. Wait for in-flight calls and transactions to finish. -3. Apply the migrations with provider traffic still stopped, then restart only - new binaries containing these fixes and updated direct SQL callers. -4. Review retention cutoffs before resuming delete and prune jobs. Expect a +3. Start one process using the new binary with `MigrationPolicy::ApplyAll` first. + It applies the migrations during provider initialization; keep provider + traffic stopped until initialization succeeds. +4. Restart the remaining processes using only new binaries containing these fixes + and updated direct SQL callers. +5. Review retention cutoffs before resuming delete and prune jobs. Expect a one-time wave of age-based deletions of old continue-as-new generations whose completion timestamps have now been recovered. From ef49fcf6d7ad27f96e2d9040e9a23696a4057339 Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Thu, 19 Nov 2026 19:06:11 +0000 Subject: [PATCH 10/10] Use released Duroxide 0.2.0 in the provider and stress harness The runtime now retries activity completion acknowledgements, including after a committed response was lost. Register the upstream duplicate-ack validation to ensure those retries cannot enqueue a second completion, and align the heterogeneous-worker test with at-least-once delivery. Keep the worker-queue progress implementation in the separately coordinated PR #51; retain this PR's migrations 0027/0028 and the current package release metadata. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 9 +++++++++ Cargo.toml | 2 +- pg-stress/Cargo.toml | 2 +- tests/postgres_provider_test.rs | 1 + tests/session_e2e_tests.rs | 3 ++- 5 files changed, 14 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 678b8b4..2794f41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 It locks only instances with deletion candidates. Public-schema cleanup also removes the batch-pruning function. +### Changed + +- Update the provider and stress harness to Duroxide `0.2.0`. Provider trait + signatures and stored payload formats are unchanged. The runtime now retries + transient activity acknowledgement failures; the new upstream validation + verifies that a duplicate acknowledgement fails permanently and cannot enqueue + a second completion. Activity-admission worker-queue progress support is tracked + separately in [#51](https://github.com/microsoft/duroxide-pg/pull/51). + ### Upgrading - **Migrations `0027` and `0028` require a fully drained upgrade.** Pause delete diff --git a/Cargo.toml b/Cargo.toml index b10b01b..ac8963c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ exclude = [ ] [dependencies] -duroxide = { version = "0.1.32", features = ["provider-test"] } +duroxide = { version = "0.2.0", features = ["provider-test"] } async-trait = "0.1" tokio = { version = "1", features = ["full"] } sqlx = { version = "0.8", features = ["runtime-tokio-native-tls", "postgres", "chrono"], default-features = false } diff --git a/pg-stress/Cargo.toml b/pg-stress/Cargo.toml index e9f5b64..244935e 100644 --- a/pg-stress/Cargo.toml +++ b/pg-stress/Cargo.toml @@ -9,7 +9,7 @@ name = "pg-stress" path = "src/bin/pg-stress.rs" [dependencies] -duroxide = { version = "0.1.32", features = ["provider-test"] } +duroxide = { version = "0.2.0", features = ["provider-test"] } duroxide-pg = { path = ".." } tokio = { version = "1", features = ["full"] } tracing = "0.1" diff --git a/tests/postgres_provider_test.rs b/tests/postgres_provider_test.rs index 9bd6947..8c9cc3e 100644 --- a/tests/postgres_provider_test.rs +++ b/tests/postgres_provider_test.rs @@ -216,6 +216,7 @@ mod atomicity_tests { provider_validation_test!(atomicity::test_multi_operation_atomic_ack); provider_validation_test!(atomicity::test_lock_released_only_on_successful_ack); provider_validation_test!(atomicity::test_concurrent_ack_prevention); + provider_validation_test!(atomicity::test_ack_work_item_duplicate_rejected); } mod error_handling_tests { diff --git a/tests/session_e2e_tests.rs b/tests/session_e2e_tests.rs index e374a37..db32769 100644 --- a/tests/session_e2e_tests.rs +++ b/tests/session_e2e_tests.rs @@ -1975,7 +1975,8 @@ async fn test_multi_worker_heterogeneous_config() { let a = worker_a_sessions.load(Ordering::SeqCst); let b = worker_b_sessions.load(Ordering::SeqCst); - assert_eq!(a + b, 3, "Total should be 3, got A={a} B={b}"); + // At-least-once delivery permits another invocation after an ack failure or lease expiry. + assert!(a + b >= 3, "Total should be at least 3, got A={a} B={b}"); assert!( b >= 1, "Worker B should handle at least 1 session (overflow from A's max_sessions=1), got A={a} B={b}"