Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: durable-workflow.v2.worker-protocol-api
version: "67"
version: "68"
summary: Durable Workflow worker-plane HTTP+JSON API
description: >
Normative OpenAPI specification for the worker-plane HTTP+JSON API:
Expand Down Expand Up @@ -1874,6 +1874,13 @@ components:
additionalProperties: true
required: [supported_workflow_task_commands, workflow_task_poll_request_idempotency, workflow_memo_updates, message_streams, typed_search_attributes, condition_wait_occurrence_identity, update_validation_tasks, synchronous_update_validation, local_activities, sticky_execution]
properties:
condition_wait_input_order:
type: string
const: durable_receipt_order
description: >
This Server can replay history marked for durable input ordering.
Workers that understand the marker register condition_wait_input_order.
A separate field on the workflow lease permits opening a new marked wait.
condition_wait_occurrence_deadline:
type: boolean
description: >
Expand Down Expand Up @@ -2452,6 +2459,20 @@ components:
workflow_task_attempt: { type: integer, minimum: 1 }
lease_owner: { type: string, minLength: 1 }
lease_expires_at: { type: string, format: date-time }
condition_wait_input_order_authoring:
type: boolean
const: true
description: >
This lease may author a new ordered condition wait. Omission keeps
existing authoring behavior and does not disable replay of marked
history. Retried polls for the same claim preserve this field.
condition_wait_pending_input_sequence:
type: [integer, "null"]
minimum: 1
description: >
For a marked run, the first accepted signal or update that has not
settled in the task snapshot. Null means all accepted inputs seen
by this claim have settled. Omission means no snapshot was supplied.
sticky_worker_id:
type: [string, "null"]
description: Process identity holding this run's optional sticky affinity.
Expand Down Expand Up @@ -3685,6 +3706,37 @@ components:
description: >
The original authored timeout T of the occurrence, distinct from
timeout_seconds, which is the worker's remaining replay budget.
condition_wait_input_order:
type: string
const: durable_receipt_order
x-durable-workflow-server-capability: condition_wait_input_order
description: >
Requires deadline_policy occurrence and permission on the
original workflow claim. Its original timer bounds the
eligible applied effects by receipt sequence.
- if:
properties:
type: { const: resolve_condition_wait }
required: [type]
then:
required: [condition_wait_id, satisfied]
x-durable-workflow-worker-capability: condition_wait_input_order
properties:
condition_wait_id: { type: string, minLength: 1, maxLength: 191 }
satisfied: { type: boolean }
input_receipt_sequence:
type: integer
minimum: 1
description: Receipt of the applied input that first satisfied the predicate.
competing_resolution_event_id:
type: string
minLength: 1
maxLength: 191
description: >
With satisfied false, selects the exact competing terminal
event identified by SelectionCandidateReady after evaluating
the earlier eligible inputs. This leaves the condition wait
itself unresolved.
- if:
properties:
type: { const: record_local_activity }
Expand Down
21 changes: 21 additions & 0 deletions rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,27 @@ definitions and takes the database out of its staged state. The trigger
definer requires access to the checkpoint table for as long as the triggers
are installed.

## Rolling out durable input ordering for timed waits

Leave `DW_ORDERED_CONDITION_WAIT_AUTHORING` unset while replacing Server
processes. This lets the new Server and older versions share an existing
database before any workflow opens a wait using the new ordering. Deploy
compatible SDK workers before enabling authoring.

Enable `DW_ORDERED_CONDITION_WAIT_AUTHORING=1` only after every Server that
can process the database uses a release that understands ordered waits.
Include maintenance processes and instances eligible to return after
failover. The setting only allows new workflow leases to open ordered
waits. Compatible Servers continue to process marked history and
compatible workers continue to replay it with authoring disabled.

To stop opening new ordered waits, remove the setting from every Server
and let previously admitted workflow leases settle or expire. Once a
database contains marked history, any Server that may process that
database must understand the marker. Rolling back past the compatible
version requires a pre-activation database restore under the normal data
recovery process.

## Workflow task lease loss

Run descriptions, observations and lists expose `task_attention` when an
Expand Down
4 changes: 3 additions & 1 deletion rust/src/config_audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,8 @@ pub fn audit(environment: &BTreeMap<String, String>) -> Report {
fn native_only(name: &str) -> bool {
matches!(
name,
"DW_BIND_ADDRESS" | "DW_ENV" | "DW_RUST_EXPERIMENTAL" | "DW_RUST_MAINTENANCE_LOOP" | "DW_UPGRADE_BACKUP_FINGERPRINT"
"DW_BIND_ADDRESS" | "DW_ENV" | "DW_RUST_EXPERIMENTAL" | "DW_RUST_MAINTENANCE_LOOP"
| "DW_ORDERED_CONDITION_WAIT_AUTHORING" | "DW_UPGRADE_BACKUP_FINGERPRINT"
)
|| ["DW_RUST_UPGRADE_QUEUE_", "DW_SCHEMA_TEST_", "DW_TAKEOVER_TEST_", "DW_TEST_"]
.iter()
Expand Down Expand Up @@ -827,6 +828,7 @@ mod tests {
("DW_ENV_AUDIT_STRICT", "1"),
("DW_RUST_EXPERIMENTAL", "1"),
("DW_RUST_MAINTENANCE_LOOP", "1"),
("DW_ORDERED_CONDITION_WAIT_AUTHORING", "1"),
("DW_BIND_ADDRESS", "0.0.0.0:8080"),
];
let report = audit(&environment(&shipped));
Expand Down
7 changes: 7 additions & 0 deletions rust/src/runtime/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ pub(super) trait Backend: Database {
const TIMER_SCHEDULE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='TimerScheduled' AND payload->>'timer_id'=$2 ORDER BY sequence DESC LIMIT 1";
/// The history sequence of a signal's `SignalReceived` event.
const SIGNAL_RECEIVED_SEQUENCE_SQL: &str = "SELECT sequence FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SignalReceived' AND payload->>'signal_id'=$2 ORDER BY sequence LIMIT 1";
const ORDERED_CONDITION_HISTORY: &str = "SELECT 1 FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='ConditionWaitOpened' AND payload->>'condition_wait_input_order'='durable_receipt_order' LIMIT 1";
// PostgreSQL compares text case-sensitively.
const RUN_COMMANDS_SQL: &str =
super::store::run_commands_sql!(
Expand All @@ -140,6 +141,7 @@ pub(super) trait Backend: Database {
"substr(c.payload,1,23)='dw-external-payload:v1:'"
);
const SELECTION_RESOLUTION_SQL: &str = "SELECT id,payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SelectionResolved' AND payload->>'selection_group_id'=$2 ORDER BY sequence LIMIT 1";
const SELECTION_CANDIDATE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SelectionCandidateReady' AND payload->>'selection_group_id'=$2 ORDER BY sequence LIMIT 1";
// Frozen run command/task repair counters use each backend's actual width.
const REPAIR_COUNTER_MAX: i64 = i32::MAX as i64;
const RANGE_REPAIR_TASK_SQL: &str = "SELECT * FROM workflow_tasks WHERE workflow_run_id=$1 AND namespace=$2 AND task_type='workflow' AND status='failed' AND payload->>'replay_blocked'='true' ORDER BY CASE WHEN available_at IS NULL THEN 1 ELSE 0 END,available_at,created_at,id LIMIT 1";
Expand Down Expand Up @@ -350,6 +352,7 @@ WHERE r.status IN ('pending','running','waiting')
ORDER BY t.available_order,t.id LIMIT 100
"#;
const SELECTION_RESOLUTION_SQL: &str = "SELECT id,payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SelectionResolved' AND json_extract(payload,'$.selection_group_id')=$2 ORDER BY sequence LIMIT 1";
const SELECTION_CANDIDATE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SelectionCandidateReady' AND json_extract(payload,'$.selection_group_id')=$2 ORDER BY sequence LIMIT 1";
const STREAM_ITEM_REFERENCES: &str = concat!("SELECT COUNT(*) FROM workflow_durable_stream_items WHERE stream_id=$1 AND (payload_reference IS NOT NULL OR ", super::retention::reference!("payload"), ")");
const STREAM_REFERENCES: &str = PLAIN_STREAM_REFERENCES;
const RUN_STREAM_REFERENCES: &str = concat!(
Expand All @@ -374,6 +377,7 @@ ORDER BY t.available_order,t.id LIMIT 100
const TIMER_TASK_SQL: &str = "SELECT id,payload FROM workflow_tasks WHERE workflow_run_id=$1 AND task_type='timer' AND status='ready' AND json_extract(payload,'$.timer_id')=$2 AND namespace=$3";
const TIMER_SCHEDULE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='TimerScheduled' AND json_extract(payload,'$.timer_id')=$2 ORDER BY sequence DESC LIMIT 1";
const SIGNAL_RECEIVED_SEQUENCE_SQL: &str = "SELECT sequence FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='SignalReceived' AND json_extract(payload,'$.signal_id')=$2 ORDER BY sequence LIMIT 1";
const ORDERED_CONDITION_HISTORY: &str = "SELECT 1 FROM workflow_history_events WHERE workflow_run_id=$1 AND event_type='ConditionWaitOpened' AND json_extract(payload,'$.condition_wait_input_order')='durable_receipt_order' LIMIT 1";
const RUN_COMMANDS_SQL: &str =
super::store::run_commands_sql!(
"substr(s.arguments,1,30) COLLATE BINARY='dw-native-external-payload-v1:'",
Expand Down Expand Up @@ -679,6 +683,7 @@ impl Backend for MySql {
const MEMO_INHERIT_INSERT: &str = "INSERT INTO workflow_memos(workflow_run_id,workflow_instance_id,`key`,value,upserted_at_sequence,inherited_from_parent,created_at,updated_at,portable_value,portable_value_sequence) VALUES ($1,$2,$3,$4,1,true,$5,$6,$7,1)";
const MEMO_READ: &str = "SELECT `key`,value,portable_value,portable_value_sequence,upserted_at_sequence FROM workflow_memos WHERE workflow_run_id=$1 ORDER BY `key`,id LIMIT 101";
const SELECTION_RESOLUTION_SQL: &str = "SELECT id,payload FROM workflow_history_events WHERE workflow_run_id=? AND event_type='SelectionResolved' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.selection_group_id'))=? ORDER BY sequence LIMIT 1";
const SELECTION_CANDIDATE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=? AND event_type='SelectionCandidateReady' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.selection_group_id'))=? ORDER BY sequence LIMIT 1";
const BRIDGE_COMMAND: &str = "SELECT workflow_run_id,resolved_workflow_run_id FROM workflow_commands WHERE workflow_instance_id=? AND command_type=? AND status='accepted' AND BINARY JSON_UNQUOTE(JSON_EXTRACT(context,'$.server.metadata.adapter'))=BINARY ? AND BINARY JSON_UNQUOTE(JSON_EXTRACT(context,'$.server.metadata.action'))=BINARY ? AND BINARY JSON_UNQUOTE(JSON_EXTRACT(context,'$.server.metadata.idempotency_key'))=BINARY ? AND BINARY JSON_UNQUOTE(JSON_EXTRACT(context,CONCAT('$.server.metadata.',?)))=BINARY ? AND (request_id IS NULL OR BINARY request_id=BINARY ?) ORDER BY accepted_at DESC,command_sequence DESC LIMIT 1";
const REPAIR_COUNTER_MAX: i64 = u32::MAX as i64;
const RANGE_REPAIR_TASK_SQL: &str = "SELECT * FROM workflow_tasks WHERE workflow_run_id=? AND namespace=? AND task_type='workflow' AND status='failed' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.replay_blocked'))='true' ORDER BY CASE WHEN available_at IS NULL THEN 1 ELSE 0 END,available_at,created_at,id LIMIT 1";
Expand Down Expand Up @@ -712,6 +717,7 @@ impl Backend for MySql {
const TIMER_TASK_SQL: &str = "SELECT id,payload FROM workflow_tasks WHERE workflow_run_id=? AND task_type='timer' AND status='ready' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.timer_id'))=? AND BINARY namespace=BINARY ?";
const TIMER_SCHEDULE_SQL: &str = "SELECT payload FROM workflow_history_events WHERE workflow_run_id=? AND event_type='TimerScheduled' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.timer_id'))=? ORDER BY sequence DESC LIMIT 1";
const SIGNAL_RECEIVED_SEQUENCE_SQL: &str = "SELECT sequence FROM workflow_history_events WHERE workflow_run_id=? AND event_type='SignalReceived' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.signal_id'))=? ORDER BY sequence LIMIT 1";
const ORDERED_CONDITION_HISTORY: &str = "SELECT 1 FROM workflow_history_events WHERE workflow_run_id=? AND event_type='ConditionWaitOpened' AND JSON_UNQUOTE(JSON_EXTRACT(payload,'$.condition_wait_input_order'))='durable_receipt_order' LIMIT 1";
// The payload column's collation ignores case; compare bytes.
const RUN_COMMANDS_SQL: &str =
super::store::run_commands_sql!(
Expand All @@ -736,6 +742,7 @@ impl Backend for MySql {
|| sql == Self::SIGNAL_RECEIVED_SEQUENCE_SQL
|| sql == Self::RANGE_REPAIR_TASK_SQL
|| sql == Self::SELECTION_RESOLUTION_SQL
|| sql == Self::SELECTION_CANDIDATE_SQL
|| sql == Self::BRIDGE_COMMAND
|| sql == Self::ACTIVITY_OPEN_TASK_SQL
|| sql == Self::LOCAL_ACTIVITY_EXECUTIONS
Expand Down
4 changes: 3 additions & 1 deletion rust/src/runtime/completion_rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -831,8 +831,10 @@ const READS: &[(&str, &[&str])] = &[
("upsert_search_attributes", &["attributes", "attribute_types"]),
("upsert_memo", &["entries"]),
("open_condition_wait", &["condition_key", "condition_definition_fingerprint", "condition_wait_occurrence_id", "timeout_seconds",
"deadline_policy", "condition_wait_timeout_budget_seconds"]),
"deadline_policy", "condition_wait_timeout_budget_seconds",
super::wait_timeouts::CONDITION_INPUT_ORDER_FIELD]),
("open_signal_wait", &["signal_name", "timeout_seconds"]),
(super::wait_timeouts::RESOLVE_CONDITION_WAIT, &["condition_wait_id", "satisfied", "input_receipt_sequence", "competing_resolution_event_id"]),
];

/// `parallelMetadataValidationRules`' fields, read for the leaf commands.
Expand Down
11 changes: 11 additions & 0 deletions rust/src/runtime/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,17 @@ impl Runtime {
self.structural = limits;
self
}
/// Allow new ordered waits on workflow tasks claimed by this runtime.
/// Existing marked waits remain replayable with the setting disabled.
pub fn with_ordered_condition_wait_authoring(mut self, enabled: bool) -> Self {
let storage = match &*self.storage {
Storage::Sqlite(store) => Storage::Sqlite(store.with_ordered_condition_wait_authoring(enabled)),
Storage::Postgres(store) => Storage::Postgres(store.with_ordered_condition_wait_authoring(enabled)),
Storage::MySql(store) => Storage::MySql(store.with_ordered_condition_wait_authoring(enabled)),
};
self.storage = Arc::new(storage);
self
}
/// The configured history page sizes (DW_HISTORY_PAGE_SIZE_DEFAULT and _MAX).
pub(super) fn history_pages(&self) -> super::history_pages::HistoryPages {
super::history_pages::HistoryPages {
Expand Down
55 changes: 52 additions & 3 deletions rust/src/runtime/selections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ where
}
// Called immediately after the member's actual terminal event under
// the same transition lock; bind its physical durable history ID.
let event = Self::query("SELECT id,event_type,payload FROM workflow_history_events WHERE workflow_run_id=$1 ORDER BY sequence DESC LIMIT 1")
let event = Self::query("SELECT id,sequence,event_type,payload FROM workflow_history_events WHERE workflow_run_id=$1 ORDER BY sequence DESC LIMIT 1")
.bind(run_id).fetch_one(&mut **tx).await?;
if DB::string(&event, "event_type")? != event_type {
return Err(refuse(
Expand All @@ -547,17 +547,66 @@ where
} else {
member_identity(entry, identity)
};
Self::append(tx, run_id, "SelectionResolved", json!({
let mut resolution = json!({
"selection_group_id":group_id,"selection_group_base_sequence":entry["parallel_group_base_sequence"],
"selection_group_size":entry["parallel_group_size"],"member_key":entry["selection_member_key"],
"member_index":entry["selection_member_index"],"member_base_sequence":entry["selection_member_base_sequence"],
"member_size":entry["selection_member_size"],"operation_kind":operation_kind,
"operation_identity":identity,"outcome":outcome(event_type),
"resolution_event_id":DB::string(&event,"id")?,"resolution_event_type":event_type,
}), None, None).await?;
});
if kind == "child"
&& Self::ordered_selection_has_open_condition(tx, run_id, group_id).await?
{
if Self::query(DB::SELECTION_CANDIDATE_SQL).bind(run_id).bind(group_id)
.fetch_optional(&mut **tx).await?.is_none()
{
// The child terminal is authoritative. The winner waits for
// the parent's predicate over inputs received before it.
resolution["resolution_event_sequence"] = json!(DB::number(&event, "sequence")?);
Self::append(tx, run_id, "SelectionCandidateReady", resolution, None, None).await?;
}
return Ok(false);
}
Self::append(tx, run_id, "SelectionResolved", resolution, None, None).await?;
Ok(true)
}

async fn ordered_selection_has_open_condition(
tx: &mut Transaction<'_, DB>,
run_id: &str,
group_id: &str,
) -> Result<bool> {
if Self::query(DB::ORDERED_CONDITION_HISTORY)
.bind(run_id).fetch_optional(&mut **tx).await?.is_none()
{
return Ok(false);
}
let waits = Self::waits(tx, run_id).await?;
Ok(waits.conditions.iter().filter(|wait| wait.is_open())
.filter_map(|wait| waits.condition_opening(&wait.id))
.any(|opening| super::wait_timeouts::uses_condition_input_order(&opening.payload)
&& selection(&opening.payload).is_some_and(|entry| entry["parallel_group_id"] == group_id)))
}

pub(super) async fn unresolved_selection_candidate(
tx: &mut Transaction<'_, DB>,
run_id: &str,
opening: &Value,
) -> Result<Option<Value>> {
let Some(group_id) = selection(opening).and_then(|entry| entry["parallel_group_id"].as_str()) else {
return Ok(None);
};
if Self::query(DB::SELECTION_RESOLUTION_SQL)
.bind(run_id).bind(group_id).fetch_optional(&mut **tx).await?.is_some()
{
return Ok(None);
}
let candidate = Self::query(DB::SELECTION_CANDIDATE_SQL)
.bind(run_id).bind(group_id).fetch_optional(&mut **tx).await?;
candidate.map(|row| DB::document_row(&row, "payload")).transpose()
}

/// Wakes the workflow after a member's close, or returns `None` when
/// published PHP's `ParallelChildGroup::shouldWakeParentOnClosure` would
/// not: a successful close inside an all-of group waits until every
Expand Down
Loading