Skip to content
Durable Workflowrust

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