Skip to main content

durable_workflow/
update_validation.rs

1//! Synchronous pre-accept update validation (durable-workflow/.github#234).
2//!
3//! A worker that registers an update validator advertises it in the
4//! workflow command contract's `update_validators` list and the
5//! `update_validation_tasks` capability. A Server that advertises
6//! `synchronous_update_validation` then holds each such update until a
7//! validator-capable worker approves it. The worker's workflow long poll asks
8//! for `task_kinds: ["workflow", "update_validation"]`, so one capacity
9//! reservation covers either kind. A validation task is answered by
10//! reconstructing the run from its committed history, as a query does, and
11//! invoking only the validator: the update handler never runs, and no
12//! workflow command is ever completed for the task. An approval lets the
13//! Server accept the update; a rejection is recorded by the Server as a
14//! rejected update and is never delivered to workflow code.
15
16use crate::{
17    path_segment, AvroValue, Boundary, Client, Error, ManagedPollOutcome, QueryContext, QueryTask,
18    RegisteredQuery, RegistrationKind, RequestProtocol, Result, Worker,
19};
20use serde::Serialize;
21use serde_json::{json, Value};
22use std::{
23    any::TypeId,
24    collections::BTreeMap,
25    fmt,
26    sync::{atomic::Ordering, Arc, Mutex, PoisonError},
27    time::Duration,
28};
29
30/// The Server's failure reason for a validator that refused the update.
31pub const UPDATE_VALIDATOR_REJECTED: &str = "update_validator_rejected";
32/// The worker's failure reason when it could not run the validator.
33pub const UPDATE_VALIDATION_WORKER_FAILED: &str = "update_validation_worker_failed";
34
35const WORKFLOW_POLL_PATH: &str = "/worker/workflow-tasks/poll";
36const TASK_KINDS: [&str; 2] = ["workflow", "update_validation"];
37const COMMAND_REFUSED_TYPE: &str = "UpdateValidatorCommandRefused";
38const VALIDATOR_ERROR_TYPE: &str = "UpdateValidatorError";
39const INVALID_SIGNAL_ARGUMENTS: &str = "invalid_signal_arguments";
40const PROTECTED_SIGNAL_VALIDATION_FAILED: &str = "protected_signal_validation_failed";
41
42/// Completion refusals that mean another attempt or worker owns the task now.
43const FENCED_REASONS: [&str; 7] = [
44    "update_validation_task_not_found",
45    "duplicate_update_validation_completion",
46    "update_validation_task_not_leased",
47    "update_validation_lease_owner_mismatch",
48    "stale_update_validation_completion",
49    "update_validation_lease_expired",
50    "update_validator_worker_lost",
51];
52
53/// Why an update validator refused an update.
54///
55/// Return it from a validator registered with
56/// [`Worker::register_update_validator`] or
57/// [`Worker::register_replayed_update_validator`]. The update is rejected
58/// before acceptance: the Server records a rejected update with reason
59/// `update_validator_rejected`, the update handler never runs and workflow
60/// code never sees the update. The caller receives the message and validation
61/// errors through [`Error::update_validator_rejection`].
62#[derive(Clone, Debug, PartialEq, Eq)]
63#[non_exhaustive]
64pub struct UpdateRejection {
65    /// The rejection message returned to the caller.
66    pub message: String,
67    /// An optional application failure type, recorded on the validation task.
68    pub failure_type: Option<String>,
69    /// Field names mapped to their validation messages.
70    pub validation_errors: BTreeMap<String, Vec<String>>,
71}
72
73impl UpdateRejection {
74    /// Reject an update with a message.
75    pub fn new(message: impl Into<String>) -> Self {
76        Self {
77            message: message.into(),
78            failure_type: None,
79            validation_errors: BTreeMap::new(),
80        }
81    }
82
83    /// Name the application failure type.
84    pub fn with_type(mut self, failure_type: impl Into<String>) -> Self {
85        self.failure_type = Some(failure_type.into());
86        self
87    }
88
89    /// Add one validation message for a field.
90    pub fn with_validation_error(
91        mut self,
92        field: impl Into<String>,
93        message: impl Into<String>,
94    ) -> Self {
95        self.validation_errors
96            .entry(field.into())
97            .or_default()
98            .push(message.into());
99        self
100    }
101
102    fn wire(&self, reason: &str) -> Value {
103        let mut failure = json!({"message": self.message, "reason": reason});
104        if let Some(failure_type) = &self.failure_type {
105            failure["type"] = json!(failure_type);
106        }
107        if !self.validation_errors.is_empty() {
108            failure["validation_errors"] = json!(self.validation_errors);
109        }
110        failure
111    }
112}
113
114impl fmt::Display for UpdateRejection {
115    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
116        formatter.write_str(&self.message)
117    }
118}
119
120impl std::error::Error for UpdateRejection {}
121
122impl From<Error> for UpdateRejection {
123    fn from(error: Error) -> Self {
124        match error {
125            Error::UpdateRejection(rejection) => rejection,
126            error => Self::new(error.to_string()).with_type(VALIDATOR_ERROR_TYPE),
127        }
128    }
129}
130
131impl From<serde_json::Error> for UpdateRejection {
132    fn from(error: serde_json::Error) -> Self {
133        Self::new(error.to_string()).with_type(VALIDATOR_ERROR_TYPE)
134    }
135}
136
137/// The refusal for a validator that added a workflow command.
138pub(crate) fn scheduled_work_refusal() -> UpdateRejection {
139    UpdateRejection::new(
140        "update validators are read-only: the validator tried to schedule durable workflow work",
141    )
142    .with_type(COMMAND_REFUSED_TYPE)
143}
144
145/// An update the Server rejected because the workflow's validator refused it.
146///
147/// Nothing was accepted: the update handler did not run and workflow code
148/// never saw the update. Read it with [`Error::update_validator_rejection`].
149/// `body` is the Server's full answer.
150#[derive(Clone, Debug, PartialEq)]
151#[non_exhaustive]
152pub struct UpdateValidatorRejected {
153    pub status: u16,
154    pub workflow_id: Option<String>,
155    pub run_id: Option<String>,
156    pub update_name: Option<String>,
157    pub update_id: Option<String>,
158    pub message: String,
159    pub validation_errors: BTreeMap<String, Vec<String>>,
160    pub body: Value,
161}
162
163impl Error {
164    /// Whether the workflow's update validator rejected the update before
165    /// acceptance (HTTP 422, `reason: "update_validator_rejected"`).
166    pub fn is_update_validator_rejected(&self) -> bool {
167        self.update_validator_rejection().is_some()
168    }
169
170    /// The details of an update the workflow's validator rejected.
171    pub fn update_validator_rejection(&self) -> Option<UpdateValidatorRejected> {
172        let Self::Http { status, body } = self else {
173            return None;
174        };
175        let body: Value = serde_json::from_str(body).ok()?;
176        if body.get("reason").and_then(Value::as_str) != Some(UPDATE_VALIDATOR_REJECTED) {
177            return None;
178        }
179        let string = |name: &str| {
180            body.get(name)
181                .and_then(Value::as_str)
182                .filter(|value| !value.is_empty())
183                .map(str::to_string)
184        };
185        let validation_errors = body
186            .get("validation_errors")
187            .and_then(Value::as_object)
188            .map(|fields| {
189                fields
190                    .iter()
191                    .map(|(field, messages)| {
192                        let messages = messages
193                            .as_array()
194                            .map(|messages| {
195                                messages
196                                    .iter()
197                                    .filter_map(Value::as_str)
198                                    .map(str::to_string)
199                                    .collect()
200                            })
201                            .unwrap_or_default();
202                        (field.clone(), messages)
203                    })
204                    .collect()
205            })
206            .unwrap_or_default();
207        Some(UpdateValidatorRejected {
208            status: status.as_u16(),
209            workflow_id: string("workflow_id"),
210            run_id: string("run_id"),
211            update_name: string("update_name"),
212            update_id: string("update_id"),
213            message: string("message")
214                .unwrap_or_else(|| "the update validator rejected the request".to_string()),
215            validation_errors,
216            body,
217        })
218    }
219
220    /// Whether a validated update could not be validated, for example
221    /// because no validator-capable worker answered before the Server's
222    /// deadline or the worker could not run the validator
223    /// (`outcome: "update_validation_failed"`). Nothing was accepted. The
224    /// Server's `reason` and `retryable` fields are in the error body.
225    pub fn is_update_validation_failed(&self) -> bool {
226        let Self::Http { body, .. } = self else {
227            return false;
228        };
229        serde_json::from_str::<Value>(body).is_ok_and(|body| {
230            body.get("outcome").and_then(Value::as_str) == Some("update_validation_failed")
231        })
232    }
233}
234
235/// A validation task leased by a multiplexed workflow poll, parked until the
236/// poller that holds the capacity reservation runs it.
237#[derive(Debug, Default)]
238pub(crate) struct ParkedTask(Mutex<Option<Value>>);
239
240impl ParkedTask {
241    pub(crate) fn take(&self) -> Option<Value> {
242        self.0.lock().unwrap_or_else(PoisonError::into_inner).take()
243    }
244}
245
246pub(crate) type Slot = Arc<ParkedTask>;
247
248impl Client {
249    /// The multiplexed poll body for a validator worker's workflow poll.
250    pub(crate) fn multiplexed_workflow_poll_body<B: Serialize + ?Sized>(
251        &self,
252        path: &str,
253        body: &B,
254    ) -> Result<Option<Value>> {
255        if self.update_validation_slot.is_none() || path != WORKFLOW_POLL_PATH {
256            return Ok(None);
257        }
258        let mut body = serde_json::to_value(body)?;
259        body["task_kinds"] = json!(TASK_KINDS);
260        Ok(Some(body))
261    }
262
263    /// Move a leased update-validation task out of a workflow poll answer.
264    pub(crate) fn park_update_validation_task(&self, answer: &mut Value) -> Result<()> {
265        let Some(slot) = &self.update_validation_slot else {
266            return Ok(());
267        };
268        match answer["task"].get("task_kind").and_then(Value::as_str) {
269            None | Some("workflow") => Ok(()),
270            Some("update_validation") => {
271                let task = answer["task"].take();
272                *slot.0.lock().unwrap_or_else(PoisonError::into_inner) = Some(task);
273                Ok(())
274            }
275            Some(other) => Err(Error::Codec(format!(
276                "multiplexed workflow poll returned unsupported task_kind {other:?}"
277            ))),
278        }
279    }
280
281    /// Approve one leased update-validation task so the Server accepts its
282    /// update. `lease_owner` and `update_validation_attempt` fence the
283    /// completion to the delivery that leased it.
284    pub async fn approve_update_validation_task(
285        &self,
286        update_validation_task_id: &str,
287        lease_owner: &str,
288        update_validation_attempt: u64,
289    ) -> Result<Value> {
290        let path = format!(
291            "/worker/update-validation-tasks/{}/approve",
292            path_segment("update_validation_task_id", update_validation_task_id)?
293        );
294        self.request_json(
295            reqwest::Method::POST,
296            &path,
297            RequestProtocol::DefaultWorker,
298            Some(&json!({
299                "lease_owner": lease_owner,
300                "update_validation_attempt": update_validation_attempt,
301            })),
302        )
303        .await
304    }
305
306    /// Reject one leased update-validation task. Use reason
307    /// [`UPDATE_VALIDATOR_REJECTED`] for a validator's refusal and
308    /// [`UPDATE_VALIDATION_WORKER_FAILED`] when the validator could not run.
309    pub async fn reject_update_validation_task(
310        &self,
311        update_validation_task_id: &str,
312        lease_owner: &str,
313        update_validation_attempt: u64,
314        reason: &str,
315        rejection: &UpdateRejection,
316    ) -> Result<Value> {
317        let path = format!(
318            "/worker/update-validation-tasks/{}/reject",
319            path_segment("update_validation_task_id", update_validation_task_id)?
320        );
321        self.request_json(
322            reqwest::Method::POST,
323            &path,
324            RequestProtocol::DefaultWorker,
325            Some(&json!({
326                "lease_owner": lease_owner,
327                "update_validation_attempt": update_validation_attempt,
328                "failure": if self.protection_enabled() {
329                    let message = match reason {
330                        INVALID_SIGNAL_ARGUMENTS => "Protected signal argument validation failed.",
331                        PROTECTED_SIGNAL_VALIDATION_FAILED => "Protected signal validation failed.",
332                        "invalid_update_arguments" => "Protected update argument validation failed.",
333                        _ => "Protected update validation failed.",
334                    };
335                    UpdateRejection::new(message).wire(reason)
336                } else {
337                    rejection.wire(reason)
338                },
339            })),
340        )
341        .await
342    }
343}
344
345/// `_server_supports_update_validation_tasks` in the Python SDK: the Server
346/// advertises synchronous validation with an atomic multiplexed workflow poll.
347pub(crate) fn server_supports_update_validation_tasks(info: &Value) -> bool {
348    let capabilities = &info["worker_protocol"]["server_capabilities"];
349    if capabilities["update_validation_tasks"] != true {
350        return false;
351    }
352    let semantics = &capabilities["synchronous_update_validation"];
353    let poll = &semantics["task_poll"];
354    semantics["supported"] == true
355        && semantics["acceptance_boundary"] == "validator_approved"
356        && semantics["worker_capability"] == crate::UPDATE_VALIDATION_TASKS_CAPABILITY
357        && semantics["workflow_contract_field"] == "update_validators"
358        && poll["strategy"] == "multiplexed"
359        && poll["endpoint"] == WORKFLOW_POLL_PATH
360        && poll["request_field"] == "task_kinds"
361        && poll["response_discriminator"] == "task.task_kind"
362        && poll["task_kinds"].as_array().is_some_and(|kinds| {
363            TASK_KINDS
364                .iter()
365                .all(|kind| kinds.iter().any(|offered| offered == kind))
366        })
367}
368
369fn fenced(error: &Error) -> Option<String> {
370    let Error::Http { body, .. } = error else {
371        return None;
372    };
373    let reason = serde_json::from_str::<Value>(body)
374        .ok()?
375        .get("reason")?
376        .as_str()?
377        .to_string();
378    FENCED_REASONS.contains(&reason.as_str()).then_some(reason)
379}
380
381fn validator_name(update_name: &str) -> String {
382    format!("{update_name}#validator")
383}
384
385impl Worker {
386    /// Register a validator for a workflow update.
387    ///
388    /// The Server runs it before accepting the update. Returning an
389    /// [`UpdateRejection`] rejects the update with reason
390    /// `update_validator_rejected`: the update handler never runs and no
391    /// acceptance is recorded. Returning `Ok(())` approves it, and the Server
392    /// then accepts the update and the worker runs its handler as usual.
393    ///
394    /// The validator receives the same arguments as the update handler and a
395    /// read-only [`QueryContext`] over the run's committed history, so it has
396    /// no way to schedule durable work. It is not run again on replay. The
397    /// update must also be registered with [`Worker::register_update`] (or
398    /// the Avro variant) before [`Worker::register`]; registration refuses a
399    /// Server that does not advertise synchronous update validation. A
400    /// duplicate validator for the same update is reported as the update
401    /// handler name followed by `#validator`.
402    ///
403    /// A validator cannot schedule durable work; this does not compile:
404    ///
405    /// ```compile_fail
406    /// # fn configure(worker: &mut durable_workflow::Worker) {
407    /// worker.register_update_validator("orders", "approve", |ctx, _args| {
408    ///     let _timer = ctx.sleep(std::time::Duration::from_secs(1));
409    ///     Ok(())
410    /// });
411    /// # }
412    /// ```
413    #[track_caller]
414    pub fn register_update_validator<F>(
415        &mut self,
416        workflow_type: impl Into<String>,
417        update_name: impl Into<String>,
418        validator: F,
419    ) where
420        F: Fn(QueryContext, Value) -> std::result::Result<(), UpdateRejection>
421            + Send
422            + Sync
423            + 'static,
424    {
425        let validator = Arc::new(validator);
426        self.insert_update_validator::<F>(
427            workflow_type.into(),
428            update_name.into(),
429            "register_update_validator",
430            RegisteredQuery::Snapshot(Arc::new(move |ctx, args: AvroValue| {
431                let validator = Arc::clone(&validator);
432                Box::pin(async move {
433                    let args = args.into_json()?;
434                    approve(validator(ctx, args))
435                })
436            })),
437        );
438    }
439
440    /// Register an update validator on the lossless fixed Avro Value surface.
441    #[track_caller]
442    pub fn register_update_validator_avro_value<F>(
443        &mut self,
444        workflow_type: impl Into<String>,
445        update_name: impl Into<String>,
446        validator: F,
447    ) where
448        F: Fn(QueryContext, AvroValue) -> std::result::Result<(), UpdateRejection>
449            + Send
450            + Sync
451            + 'static,
452    {
453        let validator = Arc::new(validator);
454        self.insert_update_validator::<F>(
455            workflow_type.into(),
456            update_name.into(),
457            "register_update_validator_avro_value",
458            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
459                let validator = Arc::clone(&validator);
460                Box::pin(async move { approve(validator(ctx, args)) })
461            })),
462        );
463    }
464
465    /// Register an update validator that reads the workflow's replayed
466    /// instance state.
467    ///
468    /// The workflow type must use [`Worker::register_replayed_workflow`] with
469    /// the same state type `S`. The worker reconstructs the state from
470    /// committed history, as for a replayed query, and passes the validator a
471    /// detached snapshot, so state changes are discarded. If the validator
472    /// adds a workflow command to the reconstructed run (for example through
473    /// a [`crate::WorkflowContext`] kept in state), the update is rejected
474    /// with failure type `UpdateValidatorCommandRefused` and nothing is
475    /// scheduled. Otherwise this behaves like
476    /// [`Worker::register_update_validator`].
477    #[track_caller]
478    pub fn register_replayed_update_validator<S, F>(
479        &mut self,
480        workflow_type: impl Into<String>,
481        update_name: impl Into<String>,
482        validator: F,
483    ) where
484        S: Clone + Send + Sync + 'static,
485        F: Fn(QueryContext, Arc<S>, Value) -> std::result::Result<(), UpdateRejection>
486            + Send
487            + Sync
488            + 'static,
489    {
490        let validator = Arc::new(validator);
491        self.insert_update_validator::<F>(
492            workflow_type.into(),
493            update_name.into(),
494            "register_replayed_update_validator",
495            RegisteredQuery::Replayed {
496                state_type: TypeId::of::<S>(),
497                handler: Arc::new(move |ctx, state, args| {
498                    let state = state.downcast::<S>().map_err(|_| {
499                        "registered update validator state type does not match the replayed workflow state"
500                            .to_string()
501                    })?;
502                    let validator = Arc::clone(&validator);
503                    Ok(Box::pin(async move {
504                        let args = args.into_json()?;
505                        approve(validator(ctx, state, args))
506                    }))
507                }),
508            },
509        );
510    }
511
512    #[track_caller]
513    fn insert_update_validator<F>(
514        &mut self,
515        workflow_type: String,
516        update_name: String,
517        method: &'static str,
518        validator: RegisteredQuery,
519    ) {
520        if !self.admit_registration::<F>(
521            RegistrationKind::Update,
522            Some(&workflow_type),
523            &validator_name(&update_name),
524            method,
525        ) {
526            return;
527        }
528        self.update_validators
529            .entry(workflow_type)
530            .or_default()
531            .insert(update_name, validator);
532    }
533
534    pub(crate) fn has_update_validators(&self) -> bool {
535        self.update_validators
536            .values()
537            .any(|validators| !validators.is_empty())
538    }
539
540    /// A fresh parking slot for one workflow poll, or `None` without validators.
541    pub(crate) fn update_validation_poll_slot(&self) -> Result<Option<Slot>> {
542        if !self.worker_needs_update_validation() {
543            return Ok(None);
544        }
545        if !self.update_validation_confirmed.load(Ordering::SeqCst) {
546            return Err(Error::WorkerLoop(
547                "update_validation_registration_unconfirmed: register this validator worker before polling workflow tasks".into(),
548            ));
549        }
550        Ok(Some(Arc::default()))
551    }
552
553    /// Refuse registration unless every validator has an update handler and
554    /// the Server advertises synchronous validation with multiplexed polling.
555    pub(crate) async fn require_update_validation_support(&self) -> Result<()> {
556        for (workflow_type, validators) in &self.update_validators {
557            for update_name in validators.keys() {
558                let handled = self.workflows.contains_key(workflow_type)
559                    && self
560                        .updates
561                        .get(workflow_type)
562                        .is_some_and(|updates| updates.contains_key(update_name));
563                if !handled {
564                    return Err(Error::UpdateValidationUnavailable(format!(
565                        "update validator {workflow_type}.{update_name} has no registered workflow update handler"
566                    )));
567                }
568                if let Some(RegisteredQuery::Replayed { state_type, .. }) =
569                    validators.get(update_name)
570                {
571                    let workflow = &self.workflows[workflow_type];
572                    if workflow.replay.is_none() || workflow.state_type != Some(*state_type) {
573                        return Err(Error::UpdateValidationUnavailable(format!(
574                            "replayed update validator {workflow_type}.{update_name} needs the workflow registered with register_replayed_workflow and the same state type"
575                        )));
576                    }
577                }
578            }
579        }
580        // Discovery uses the Worker credential, including worker-only Clients.
581        let info: Value = self
582            .client
583            .retry_cluster_info(|| {
584                self.client
585                    .request_json_unresolved_with_timeout::<Value, Value>(
586                        reqwest::Method::GET,
587                        "/cluster/info",
588                        RequestProtocol::DefaultWorker,
589                        None,
590                        Duration::from_secs(5),
591                    )
592            })
593            .await?;
594        if self.client.protection_enabled()
595            && !self.updates.is_empty()
596            && info["worker_protocol"]["server_capabilities"]
597                [crate::worker_payload::PROTECTED_UPDATE_TASKS]
598                != true
599        {
600            return Err(Error::UpdateValidationUnavailable(
601                "Server does not advertise protected pre-accept update validation".into(),
602            ));
603        }
604        if self.worker_uses_protected_signals()
605            && info["worker_protocol"]["server_capabilities"]
606                [crate::worker_payload::PROTECTED_SIGNAL_VALIDATION]
607                != true
608        {
609            return Err(Error::UpdateValidationUnavailable(
610                "Server does not advertise protected pre-accept signal validation".into(),
611            ));
612        }
613        if !server_supports_update_validation_tasks(&info) {
614            return Err(Error::UpdateValidationUnavailable(
615                "this worker declares update validators, but the Server does not advertise synchronous pre-accept update validation with atomic multiplexed workflow/update-validation polling; refusing registration so validated updates cannot be accepted without validator approval".into(),
616            ));
617        }
618        Ok(())
619    }
620
621    /// Run one leased update-validation task and approve or reject it.
622    ///
623    /// Completion refusals that fence a stale delivery and other completion
624    /// failures are logged; the Server's lease expiry owns redelivery.
625    pub(crate) async fn execute_update_validation_task(&self, task: Value) -> ManagedPollOutcome {
626        let task_id = task["update_validation_task_id"]
627            .as_str()
628            .filter(|id| !id.is_empty())
629            .map(str::to_string);
630        let attempt = task["update_validation_attempt"]
631            .as_u64()
632            .filter(|attempt| *attempt >= 1);
633        let (Some(task_id), Some(attempt)) = (task_id, attempt) else {
634            tracing::warn!(
635                target: "durable_workflow::worker",
636                "received a malformed update validation task"
637            );
638            return ManagedPollOutcome::Handled;
639        };
640        let mut task_metrics = self
641            .metrics
642            .worker(true, "update_validation", &self.task_queue);
643        task_metrics.outcome("failed");
644        let decision = if task.get("protected_signal").is_some() {
645            self.decide_update_validation(task).await
646        } else {
647            let context = self.update_validation_interceptor_context(&task);
648            self.intercept_update_validation(context, self.decide_update_validation(task))
649                .await
650        };
651        let lease_owner = self.worker_id.clone();
652        // The answer is sent even while the worker stops, as query and
653        // workflow-task completions are: the caller is waiting on it.
654        let mut retries = 0;
655        let completed = loop {
656            let completion = match &decision {
657                Ok(()) => {
658                    self.client
659                        .approve_update_validation_task(&task_id, &lease_owner, attempt)
660                        .await
661                }
662                Err((reason, rejection)) => {
663                    self.client
664                        .reject_update_validation_task(
665                            &task_id,
666                            &lease_owner,
667                            attempt,
668                            reason,
669                            rejection,
670                        )
671                        .await
672                }
673            };
674            match completion {
675                Err(error)
676                    if crate::worker_operation_is_retryable(&error)
677                        && retries < self.retry_policy.max_retries =>
678                {
679                    retries += 1;
680                    tokio::time::sleep(crate::worker_poll_retry_delay(self.retry_policy, retries))
681                        .await;
682                }
683                completion => break completion,
684            }
685        };
686        match completed {
687            Ok(_) => task_metrics.outcome(match &decision {
688                Ok(()) => "approved",
689                Err((UPDATE_VALIDATOR_REJECTED | INVALID_SIGNAL_ARGUMENTS, _)) => "rejected",
690                Err(_) => "failed",
691            }),
692            Err(error) => match fenced(&error) {
693                Some(reason) => {
694                    task_metrics.outcome("expired");
695                    tracing::info!(
696                        target: "durable_workflow::worker",
697                        update_validation_task_id = task_id.as_str(),
698                        reason = reason.as_str(),
699                        "update validation completion was fenced"
700                    )
701                }
702                None => tracing::warn!(
703                    target: "durable_workflow::worker",
704                    update_validation_task_id = task_id.as_str(),
705                    error = %error,
706                    "failed to complete update validation task"
707                ),
708            },
709        }
710        ManagedPollOutcome::Handled
711    }
712
713    async fn resolve_validation_payloads(&self, task: Value) -> Result<Value> {
714        let mut envelope = json!({"task": task});
715        self.client
716            .resolve_runtime_payloads(
717                &mut envelope,
718                WORKFLOW_POLL_PATH,
719                RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
720            )
721            .await?;
722        Ok(envelope["task"].take())
723    }
724
725    /// Approve, or the failure reason and rejection to report.
726    pub(crate) async fn decide_update_validation(
727        &self,
728        task: Value,
729    ) -> std::result::Result<(), (&'static str, UpdateRejection)> {
730        let failed = |message: String| {
731            (
732                UPDATE_VALIDATION_WORKER_FAILED,
733                UpdateRejection::new(message),
734            )
735        };
736        let signal_failed = || {
737            (
738                PROTECTED_SIGNAL_VALIDATION_FAILED,
739                UpdateRejection::new("Protected signal validation failed."),
740            )
741        };
742        if task.get("protected_signal").is_some() {
743            let task = self
744                .resolve_validation_payloads(task)
745                .await
746                .map_err(|_| signal_failed())?;
747            return self
748                .check_protected_signal_offer(&task)
749                .map_err(|error| match error {
750                    Error::Codec(_) => (
751                        INVALID_SIGNAL_ARGUMENTS,
752                        UpdateRejection::new("Protected signal argument validation failed."),
753                    ),
754                    _ => signal_failed(),
755                });
756        }
757        let workflow_type = task["workflow_type"]
758            .as_str()
759            .filter(|value| !value.is_empty());
760        let update_name = task["update_name"]
761            .as_str()
762            .filter(|value| !value.is_empty());
763        let (Some(workflow_type), Some(update_name)) = (workflow_type, update_name) else {
764            return Err(failed(
765                "update validation task is missing workflow type or update name".into(),
766            ));
767        };
768        let (workflow_type, update_name) = (workflow_type.to_string(), update_name.to_string());
769        // Server 3.30.0 (server#1338) and later attest the run's entry
770        // instant on validation tasks, as on query tasks.
771        let replay_entry = crate::replay_clock::attestation(&task);
772        let task = self
773            .resolve_validation_payloads(task)
774            .await
775            .map_err(|error| failed(format!("cannot resolve validation payloads: {error}")))?;
776        let validator = self
777            .update_validators
778            .get(&workflow_type)
779            .and_then(|validators| validators.get(&update_name));
780        let protected = self
781            .check_protected_update_offer(&task, &update_name, validator.is_some())
782            .map_err(|_| {
783                (
784                    "invalid_update_arguments",
785                    UpdateRejection::new("Protected update argument validation failed."),
786                )
787            })?;
788        let mut query: QueryTask = serde_json::from_value(json!({
789            "query_task_id": task["update_validation_task_id"],
790            "query_task_attempt": task["update_validation_attempt"],
791            "workflow_id": task["workflow_id"],
792            "run_id": task["run_id"],
793            "workflow_type": workflow_type,
794            "query_name": update_name,
795            "payload_codec": task["payload_codec"],
796            "workflow_arguments": task["workflow_arguments"],
797            "query_arguments": task["update_arguments"],
798            "history_events": task.get("history_events").cloned().unwrap_or_else(|| json!([])),
799            "history_export": task["history_export"],
800            "run_status": task["run_status"],
801        }))
802        .map_err(|error| failed(format!("malformed update validation task: {error}")))?;
803        self.client
804            .project_query_claim(&mut query, Boundary::UpdateInput)
805            .map_err(|_| {
806                (
807                    "invalid_update_arguments",
808                    UpdateRejection::new("Protected update argument validation failed."),
809                )
810            })?;
811        crate::validate_query_task_payloads(&query)
812            .map_err(|error| failed(format!("cannot decode validation payloads: {error}")))?;
813        if !self.workflows.contains_key(&workflow_type) {
814            return Err(failed(format!(
815                "no workflow registered for type {workflow_type:?}"
816            )));
817        }
818        if !self
819            .updates
820            .get(&workflow_type)
821            .is_some_and(|updates| updates.contains_key(&update_name))
822        {
823            return Err(failed(format!("unknown update {update_name:?}")));
824        }
825        let Some(validator) = validator else {
826            if protected {
827                return Ok(());
828            }
829            return Err(failed(format!(
830                "update validator {update_name:?} is not declared"
831            )));
832        };
833        match self
834            .run_registered_query(query, validator, None, true, replay_entry)
835            .await
836        {
837            Err(failure) => Err((
838                UPDATE_VALIDATION_WORKER_FAILED,
839                UpdateRejection::new(failure.message).with_type(failure.failure_type),
840            )),
841            Ok(Ok(_)) => Ok(()),
842            Ok(Err(error)) => Err((UPDATE_VALIDATOR_REJECTED, UpdateRejection::from(error))),
843        }
844    }
845}
846
847fn approve(outcome: std::result::Result<(), UpdateRejection>) -> Result<AvroValue> {
848    outcome
849        .map(|()| AvroValue::Null)
850        .map_err(Error::UpdateRejection)
851}