Skip to main content

durable_workflow/
failure_reporting.rs

1//! Bound diagnostic data before it reaches the ordinary JSON request limit.
2use crate::{json, Result, Value};
3use serde::Serialize;
4use serde_json::Map;
5use std::io::{self, Write};
6use thiserror::Error as ThisError;
7
8// Published runtimes persist a TEXT timeline summary containing a prefix,
9// activity label and the message. Reserve room below its 65,535-byte boundary.
10pub const MESSAGE_BYTES: usize = 62 * 1024;
11pub const STACK_BYTES: usize = 128 * 1024;
12pub const DIAGNOSTIC_BYTES: usize = 64 * 1024;
13pub const REQUEST_BYTES: usize = 1024 * 1024;
14const MARKER_RESERVE: usize = 8 * 1024;
15const MARKER_KEY: &str = "sdk_failure_truncation";
16const MESSAGE_MARKER: &str = "\n[truncated; see diagnostics.sdk_failure_truncation]";
17
18/// Failure reporting refused locally; this is not an application failure decision.
19#[derive(Debug, ThisError)]
20#[non_exhaustive]
21pub enum FailureReportError {
22    #[error("failure report refused: {encoded_bytes} encoded bytes cannot fit {limit} bytes without changing required identity or failure semantics")]
23    RequiredFieldsTooLarge { encoded_bytes: usize, limit: usize },
24    #[error("failure report refused: {0}")]
25    InvalidReport(&'static str),
26}
27
28#[derive(Default)]
29struct Count(usize);
30impl Write for Count {
31    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
32        self.0 = self
33            .0
34            .checked_add(bytes.len())
35            .ok_or_else(|| io::Error::other("JSON size overflow"))?;
36        Ok(bytes.len())
37    }
38    fn flush(&mut self) -> io::Result<()> {
39        Ok(())
40    }
41}
42
43pub(super) fn encoded_size<T: Serialize + ?Sized>(value: &T) -> Result<usize> {
44    let mut count = Count::default();
45    serde_json::to_writer(&mut count, value)?;
46    Ok(count.0)
47}
48
49fn prefix(value: &str, maximum: usize) -> &str {
50    let mut end = maximum.min(value.len());
51    while !value.is_char_boundary(end) {
52        end -= 1;
53    }
54    &value[..end]
55}
56
57fn clipped(value: &str, limit: usize, marker: &str, force: bool) -> String {
58    if !force && value.len() <= limit {
59        return value.to_owned();
60    }
61    let available = limit.saturating_sub(marker.len());
62    format!("{}{marker}", prefix(value, available))
63}
64
65fn metadata_size(value: &Map<String, Value>) -> Result<usize> {
66    let metadata: Map<_, _> = value
67        .iter()
68        .filter(|(key, _)| !core(key))
69        .map(|(key, value)| (key.clone(), value.clone()))
70        .collect();
71    encoded_size(&metadata)
72}
73
74/// Local command grammar has no diagnostic object. Keep original size in its
75/// existing message field, before the workflow can observe the outcome.
76#[derive(Debug)]
77pub(super) struct LocalText {
78    prefix: String,
79    original_bytes: usize,
80}
81impl LocalText {
82    pub(super) fn new(message: &str) -> Self {
83        Self {
84            prefix: prefix(message, MESSAGE_BYTES).to_owned(),
85            original_bytes: message.len(),
86        }
87    }
88    pub(super) fn render(&self, limit: usize) -> String {
89        let marker = format!(
90            "\n[truncated: original message {} UTF-8 bytes]",
91            self.original_bytes
92        );
93        clipped(&self.prefix, limit, &marker, self.original_bytes > limit)
94    }
95}
96
97/// Match published failure/local-command normalization's PHP trim character set.
98/// Apply to the observed outcome, without rewriting the outgoing original.
99pub(super) fn committed_message(message: &str) -> &str {
100    message.trim_matches(|ch| matches!(ch, '\0' | '\t' | '\n' | '\r' | '\u{000b}' | ' '))
101}
102
103/// Fit only the current, not-yet-observed local command. Previously returned
104/// local outcomes and unrelated business payloads are fixed inputs.
105pub(super) fn fit_local(
106    body: &mut Value,
107    index: usize,
108    messages: &[(usize, LocalText)],
109    limit: usize,
110) -> Result<()> {
111    if messages.is_empty() {
112        return Ok(());
113    }
114    let limit = limit.min(REQUEST_BYTES);
115    let mut target = MESSAGE_BYTES;
116    loop {
117        let command = &mut body["commands"][index];
118        let mut diagnostic_bytes = 2_usize;
119        for (attempt, original) in messages {
120            let message = original.render(target);
121            if committed_message(&message).is_empty() {
122                return Err(FailureReportError::InvalidReport(
123                    "local failure message is empty after Server normalization",
124                )
125                .into());
126            }
127            diagnostic_bytes = diagnostic_bytes
128                .saturating_add(encoded_size(&message)?)
129                .saturating_add(1);
130            command["attempts"][*attempt]["message"] = json!(message);
131        }
132        if command.get("message").is_some() {
133            if let Some((attempt, _)) = messages.last() {
134                command["message"] = command["attempts"][*attempt]["message"].clone();
135            }
136        }
137        let size = encoded_size(body)?;
138        if size <= limit && diagnostic_bytes <= DIAGNOSTIC_BYTES {
139            return Ok(());
140        }
141        if target <= 128 {
142            return Err(FailureReportError::RequiredFieldsTooLarge {
143                encoded_bytes: size,
144                limit,
145            }
146            .into());
147        }
148        target = (target / 2).max(128);
149    }
150}
151
152fn core(key: &str) -> bool {
153    matches!(
154        key,
155        "message"
156            | "stack_trace"
157            | "type"
158            | "class"
159            | "non_retryable"
160            | "retryable"
161            | "kind"
162            | "reason"
163            | "sequence"
164            | "timeout_type"
165            | "cancelled"
166            | "malformed_output"
167    )
168}
169
170#[derive(Clone, Copy)]
171struct Budget {
172    message: usize,
173    stack: usize,
174    metadata: usize,
175    names: usize,
176}
177impl Default for Budget {
178    fn default() -> Self {
179        Self {
180            message: MESSAGE_BYTES,
181            stack: STACK_BYTES,
182            metadata: DIAGNOSTIC_BYTES,
183            names: 32,
184        }
185    }
186}
187impl Budget {
188    fn shrink(&mut self) -> bool {
189        if self.stack > 0 {
190            self.stack /= 2;
191            return true;
192        }
193        if self.message > 64 {
194            self.message = (self.message / 2).max(64);
195            return true;
196        }
197        if self.metadata > MARKER_RESERVE {
198            self.metadata = (self.metadata / 2).max(MARKER_RESERVE);
199            return true;
200        }
201        if self.names > 0 {
202            self.names /= 2;
203            return true;
204        }
205        false
206    }
207}
208
209struct Omitted {
210    count: usize,
211    names: Vec<String>,
212    maximum: usize,
213}
214impl Omitted {
215    fn new(maximum: usize) -> Self {
216        Self {
217            count: 0,
218            names: Vec::new(),
219            maximum,
220        }
221    }
222    fn add(&mut self, name: &str) -> Result<()> {
223        self.count = self.count.saturating_add(1);
224        if self.names.len() < self.maximum {
225            self.names.push(prefix(name, 128).to_owned());
226            if encoded_size(&self.names)? > 4096 {
227                self.names.pop();
228            }
229        }
230        Ok(())
231    }
232}
233
234struct Failure {
235    pointer: String,
236    original: Map<String, Value>,
237    metadata_bytes: usize,
238    field_sizes: Vec<usize>,
239    inline_diagnostics: bool,
240}
241impl Failure {
242    fn take(
243        body: &mut Value,
244        pointer: String,
245        limit: usize,
246        inline_diagnostics: bool,
247    ) -> Result<Self> {
248        let value = body
249            .pointer_mut(&pointer)
250            .ok_or(FailureReportError::InvalidReport("missing failure object"))?
251            .take();
252        let Value::Object(original) = value else {
253            return Err(FailureReportError::InvalidReport("failure must be an object").into());
254        };
255        if !original.get("message").is_some_and(Value::is_string) {
256            return Err(
257                FailureReportError::InvalidReport("failure.message must be a string").into(),
258            );
259        }
260        if original
261            .get("stack_trace")
262            .is_some_and(|v| !v.is_null() && !v.is_string())
263        {
264            return Err(FailureReportError::InvalidReport(
265                "failure.stack_trace must be a string or null",
266            )
267            .into());
268        }
269        let mut metadata_bytes = 2_usize;
270        let mut metadata_fields = 0_usize;
271        let mut field_sizes = Vec::new();
272        let mut required_bytes = 2_usize;
273        for (key, value) in &original {
274            let size = encoded_size(key)?
275                .saturating_add(encoded_size(value)?)
276                .saturating_add(1);
277            field_sizes.push(size);
278            if core(key)
279                && !matches!(key.as_str(), "message" | "stack_trace")
280                && encoded_size(value)? > limit
281            {
282                return Err(FailureReportError::RequiredFieldsTooLarge {
283                    encoded_bytes: encoded_size(value)?,
284                    limit,
285                }
286                .into());
287            }
288            if core(key) && !matches!(key.as_str(), "message" | "stack_trace") {
289                required_bytes = required_bytes.saturating_add(size).saturating_add(1);
290            }
291            if !core(key) {
292                metadata_bytes = metadata_bytes
293                    .saturating_add(size)
294                    .saturating_add(usize::from(metadata_fields > 0));
295                metadata_fields += 1;
296            }
297        }
298        if required_bytes > limit {
299            return Err(FailureReportError::RequiredFieldsTooLarge {
300                encoded_bytes: required_bytes,
301                limit,
302            }
303            .into());
304        }
305        Ok(Self {
306            pointer,
307            original,
308            metadata_bytes,
309            field_sizes,
310            inline_diagnostics,
311        })
312    }
313
314    fn render(&self, budget: Budget) -> Result<Value> {
315        let message = self.original["message"]
316            .as_str()
317            .expect("validated failure message");
318        let stack = self.original.get("stack_trace").and_then(Value::as_str);
319        let mut truncated = message.len() > budget.message
320            || stack.is_some_and(|s| budget.stack == 0 || s.len() > budget.stack)
321            || self.metadata_bytes > budget.metadata;
322        // Preserve byte ordering too when serde_json's preserve_order feature is
323        // enabled by a downstream application.
324        if !truncated {
325            return Ok(Value::Object(self.original.clone()));
326        }
327        let mut omitted = Omitted::new(budget.names);
328        let mut output = Map::new();
329        let mut used = 2_usize;
330        // Reserve space for diagnostics only when a limit already requires a marker.
331        let metadata_limit =
332            budget
333                .metadata
334                .saturating_sub(if truncated { MARKER_RESERVE } else { 0 });
335        for (index, (key, value)) in self.original.iter().enumerate() {
336            if matches!(key.as_str(), "message" | "stack_trace") {
337                continue;
338            }
339            if core(key) {
340                output.insert(key.clone(), value.clone());
341                continue;
342            }
343            let size = self.field_sizes[index].saturating_add(1);
344            if used.saturating_add(size) <= metadata_limit {
345                used += size;
346                output.insert(key.clone(), value.clone());
347            } else {
348                truncated = true;
349                omitted.add(key)?;
350            }
351        }
352        if let Some(stack) = stack {
353            let marker = format!(
354                "\n[truncated: original stack_trace {} UTF-8 bytes]",
355                stack.len()
356            );
357            if budget.stack == 0 || (stack.len() > budget.stack && budget.stack < marker.len()) {
358                omitted.add("stack_trace")?;
359            } else {
360                output.insert(
361                    "stack_trace".into(),
362                    Value::String(clipped(stack, budget.stack, &marker, false)),
363                );
364            }
365        } else if let Some(value) = self.original.get("stack_trace") {
366            output.insert("stack_trace".into(), value.clone());
367        }
368        let mut message_marker = MESSAGE_MARKER.to_owned();
369        if truncated && self.inline_diagnostics {
370            // Workflow/query-task failure schemas have no diagnostic field.
371            // Use their existing message, with exact sizing after JSON escaping.
372            message_marker = format!(
373                "\n[truncated: {}]",
374                serde_json::to_string(&json!({
375                    "original_message_bytes":message.len(),"original_stack_trace_bytes":stack.map_or(0,str::len),
376                    "original_metadata_json_bytes":self.metadata_bytes,"omitted_fields":omitted.names,"omitted_field_count":omitted.count,
377                }))?
378            );
379        } else if truncated {
380            let diagnostic = output.remove("diagnostics");
381            let mut diagnostics = match diagnostic {
382                Some(Value::Object(map)) => map,
383                Some(Value::Null) | None => Map::new(),
384                Some(other) => Map::from_iter([("original".into(), other)]),
385            };
386            if diagnostics.remove(MARKER_KEY).is_some() {
387                omitted.add("diagnostics.sdk_failure_truncation")?;
388            }
389            diagnostics.insert(
390                MARKER_KEY.into(),
391                json!({
392                    "original_message_bytes": message.len(),
393                    "original_stack_trace_bytes": stack.map_or(0,str::len),
394                    "original_metadata_json_bytes": self.metadata_bytes,
395                    "omitted_fields": omitted.names,
396                    "omitted_field_count": omitted.count,
397                }),
398            );
399            output.insert("diagnostics".into(), Value::Object(diagnostics));
400        }
401        output.insert(
402            "message".into(),
403            Value::String(clipped(message, budget.message, &message_marker, truncated)),
404        );
405        // Count the actual serialized metadata after inserting markers, including
406        // escaped field names and any wrapper around existing diagnostics.
407        if metadata_size(&output)? > budget.metadata {
408            return Err(FailureReportError::InvalidReport(
409                "truncation diagnostics exceed their serialized budget",
410            )
411            .into());
412        }
413        Ok(Value::Object(output))
414    }
415
416    fn refresh_details(&mut self, body: &Value) -> Result<()> {
417        if let Some(details) = body
418            .pointer(&self.pointer)
419            .and_then(|failure| failure.get("details"))
420        {
421            if self.original.contains_key("details") {
422                self.original.insert("details".into(), details.clone());
423                for (index, (key, value)) in self.original.iter().enumerate() {
424                    if key == "details" {
425                        self.field_sizes[index] = encoded_size(key)? + 1 + encoded_size(value)?;
426                    }
427                }
428            }
429        }
430        Ok(())
431    }
432}
433
434/// Captures originals once so later transport-budget reductions retain true sizes.
435pub(super) struct Prepared {
436    failures: Vec<Failure>,
437    texts: Vec<(String, LocalText)>,
438    mirrors: Vec<(String, String)>,
439}
440impl Prepared {
441    pub(super) fn new(body: &mut Value, path: &str, limit: usize) -> Result<Option<Self>> {
442        let parts: Vec<_> = path.trim_matches('/').split('/').collect();
443        let mut pointers = Vec::new();
444        let mut texts = Vec::new();
445        let mut mirrors = Vec::new();
446        let mut local_reports = false;
447        match parts.as_slice() {
448            ["worker", "activity-tasks" | "workflow-tasks" | "query-tasks", _, "fail"] => {
449                local_reports = true;
450                // Preserve Server validation and ordinary payload handling for
451                // malformed raw requests; their final body is still guarded.
452                if body["failure"]["message"].is_string() {
453                    pointers.push("/failure".into());
454                }
455            }
456            ["worker", "workflow-tasks", _, "complete"] => {
457                for (index, command) in body["commands"]
458                    .as_array()
459                    .into_iter()
460                    .flatten()
461                    .enumerate()
462                {
463                    if command["type"] == "fail_workflow" || command["type"] == "fail_update" {
464                        if command["exception"]["message"].is_string() {
465                            pointers.push(format!("/commands/{index}/exception"));
466                            if command.get("message").is_some() {
467                                mirrors.push((
468                                    format!("/commands/{index}/message"),
469                                    format!("/commands/{index}/exception/message"),
470                                ));
471                            }
472                        } else if let Some(message) = command["message"].as_str() {
473                            texts.push((
474                                format!("/commands/{index}/message"),
475                                LocalText::new(message),
476                            ));
477                        }
478                    }
479                    if command["type"] == "record_local_activity" {
480                        local_reports |= command.get("message").is_some()
481                            || command["attempts"]
482                                .as_array()
483                                .into_iter()
484                                .flatten()
485                                .any(|v| v.get("message").is_some());
486                    }
487                }
488            }
489            _ => return Ok(None),
490        }
491        if pointers.is_empty() && texts.is_empty() && !local_reports {
492            return Ok(None);
493        }
494        if path.len() > limit {
495            return Err(FailureReportError::RequiredFieldsTooLarge {
496                encoded_bytes: path.len(),
497                limit,
498            }
499            .into());
500        }
501        let mut failures = Vec::new();
502        let inline_diagnostics = matches!(
503            parts.as_slice(),
504            ["worker", "workflow-tasks" | "query-tasks", _, "fail"]
505        );
506        for pointer in pointers {
507            failures.push(Failure::take(body, pointer, limit, inline_diagnostics)?);
508        }
509        let prepared = Self {
510            failures,
511            texts,
512            mirrors,
513        };
514        prepared.render(body, Budget::default())?;
515        Ok(Some(prepared))
516    }
517
518    fn render(&self, body: &mut Value, budget: Budget) -> Result<()> {
519        for failure in &self.failures {
520            *body
521                .pointer_mut(&failure.pointer)
522                .expect("retained failure location") = failure.render(budget)?;
523        }
524        for (pointer, original) in &self.texts {
525            *body
526                .pointer_mut(pointer)
527                .expect("retained message location") = json!(original.render(budget.message));
528        }
529        for (target, source) in &self.mirrors {
530            let message = body
531                .pointer(source)
532                .expect("retained exception message")
533                .clone();
534            *body.pointer_mut(target).expect("retained command message") = message;
535        }
536        Ok(())
537    }
538
539    pub(super) fn can_reduce(&self) -> bool {
540        !self.failures.is_empty() || !self.texts.is_empty()
541    }
542
543    pub(super) fn encode(&mut self, body: &mut Value, limit: usize) -> Result<Vec<u8>> {
544        let limit = limit.min(REQUEST_BYTES);
545        // Keep any valid reference produced by ordinary payload externalization.
546        // Re-rendering must never restore its pre-upload Avro envelope.
547        for failure in &mut self.failures {
548            failure.refresh_details(body)?;
549        }
550        let mut budget = Budget::default();
551        if !self
552            .failures
553            .iter()
554            .any(|f| f.original.get("stack_trace").is_some_and(Value::is_string))
555        {
556            budget.stack = 0;
557        }
558        loop {
559            self.render(body, budget)?;
560            let size = encoded_size(body)?;
561            if size <= limit {
562                let bytes = serde_json::to_vec(body)?;
563                if bytes.len() <= limit {
564                    return Ok(bytes);
565                }
566                return Err(FailureReportError::RequiredFieldsTooLarge {
567                    encoded_bytes: bytes.len(),
568                    limit,
569                }
570                .into());
571            }
572            // Local history has already been observed by workflow code. Never rewrite
573            // it here; the local producer must fit it before returning its outcome.
574            if (self.failures.is_empty() && self.texts.is_empty()) || !budget.shrink() {
575                return Err(FailureReportError::RequiredFieldsTooLarge {
576                    encoded_bytes: size,
577                    limit,
578                }
579                .into());
580            }
581        }
582    }
583}
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588    fn encode(mut body: Value, limit: usize) -> (Value, Vec<u8>) {
589        let mut prepared = Prepared::new(&mut body, "/worker/activity-tasks/task/fail", limit)
590            .unwrap()
591            .unwrap();
592        let bytes = prepared.encode(&mut body, limit).unwrap();
593        assert_eq!(serde_json::from_slice::<Value>(&bytes).unwrap(), body);
594        (body, bytes)
595    }
596    #[test]
597    fn small_failure_preserves_type_flags_and_details() {
598        let input = json!({"activity_attempt_id":"attempt", "lease_owner":"owner", "failure":{"type":"Declined","message":"no","non_retryable":true,"details":null}});
599        let (output, bytes) = encode(input.clone(), REQUEST_BYTES);
600        assert_eq!(output, input);
601        assert_eq!(bytes, serde_json::to_vec(&input).unwrap());
602    }
603    #[test]
604    fn unicode_escaping_and_markers_are_included_in_actual_request_cap() {
605        let input = json!({"activity_attempt_id":"attempt", "lease_owner":"owner", "failure":{
606            "type":"Original", "non_retryable":false,"retryable":true,
607            "message":"\u{0000}界🦀".repeat(600_000),"stack_trace":"\u{0001}".repeat(3*1024*1024),
608            "diagnostics":{"causes":{"nested":"x".repeat(3*1024*1024)}}, "arbitrary":"y".repeat(3*1024*1024)}});
609        let (output, bytes) = encode(input, REQUEST_BYTES);
610        assert!(bytes.len() <= REQUEST_BYTES);
611        assert_eq!(output["failure"]["type"], "Original");
612        assert_eq!(output["failure"]["non_retryable"], false);
613        assert_eq!(output["failure"]["retryable"], true);
614        assert!(output["failure"]["message"]
615            .as_str()
616            .unwrap()
617            .contains("[truncated"));
618        assert!(output["failure"]["message"].as_str().unwrap().len() <= MESSAGE_BYTES);
619        assert!(
620            output["failure"]["diagnostics"][MARKER_KEY]["omitted_field_count"]
621                .as_u64()
622                .unwrap()
623                > 0
624        );
625    }
626    #[test]
627    fn lower_known_limit_and_exact_identity_are_preserved() {
628        let (output, bytes) = encode(
629            json!({"activity_attempt_id":"exact-attempt", "lease_owner":"exact-owner", "failure":{"type":"Original","message":"\"\\\n".repeat(1024*1024)}}),
630            4096,
631        );
632        assert!(bytes.len() <= 4096);
633        assert_eq!(output["activity_attempt_id"], "exact-attempt");
634        assert_eq!(output["lease_owner"], "exact-owner");
635        let mut impossible =
636            json!({"lease_owner":"x".repeat(4096),"failure":{"type":"T","message":"short"}});
637        let mut p = Prepared::new(&mut impossible, "/worker/activity-tasks/task/fail", 4096)
638            .unwrap()
639            .unwrap();
640        assert!(matches!(
641            p.encode(&mut impossible, 4096),
642            Err(crate::Error::FailureReporting(
643                FailureReportError::RequiredFieldsTooLarge { .. }
644            ))
645        ));
646    }
647
648    #[test]
649    fn combined_metadata_budget_includes_inserted_escaped_diagnostics() {
650        let details = json!({"codec":"avro","blob":"a".repeat(20_000)});
651        let (output, bytes) = encode(
652            json!({"failure":{
653                "message":"界".repeat(MESSAGE_BYTES),"type":"SameType","non_retryable":true,
654                "details":details,"diagnostics":{"escaped":"\u{0000}".repeat(8000)},
655                "runtime_diagnostics":{"causes":[{"nested":"x".repeat(8000)}]},
656            }}),
657            REQUEST_BYTES,
658        );
659        let failure = output["failure"].as_object().unwrap();
660        assert!(metadata_size(failure).unwrap() <= DIAGNOSTIC_BYTES);
661        assert!(bytes.len() <= REQUEST_BYTES);
662        assert_eq!(failure["type"], "SameType");
663        assert_eq!(failure["non_retryable"], true);
664        if let Some(kept) = failure.get("details") {
665            assert_eq!(kept, &details);
666        }
667        assert!(
668            failure["diagnostics"][MARKER_KEY]["omitted_field_count"]
669                .as_u64()
670                .unwrap()
671                > 0
672        );
673    }
674
675    #[test]
676    fn arbitrary_large_metadata_keys_and_values_cannot_bypass_the_cap() {
677        let mut failure = Map::from_iter([
678            ("message".into(), json!("small")),
679            ("type".into(), json!("Original")),
680        ]);
681        for index in 0..2000 {
682            failure.insert(
683                format!("{index}{}", "\u{0000}".repeat(1000)),
684                json!({"nested":"x".repeat(2000)}),
685            );
686        }
687        let (output, bytes) = encode(json!({"failure":failure}), REQUEST_BYTES);
688        assert!(bytes.len() <= REQUEST_BYTES);
689        assert!(metadata_size(output["failure"].as_object().unwrap()).unwrap() <= DIAGNOSTIC_BYTES);
690        let omitted = output["failure"]["diagnostics"][MARKER_KEY]["omitted_field_count"]
691            .as_u64()
692            .unwrap() as usize;
693        let retained = output["failure"]
694            .as_object()
695            .unwrap()
696            .keys()
697            .filter(|key| !core(key) && key.as_str() != "diagnostics")
698            .count();
699        assert_eq!(omitted + retained, 2000);
700        assert!(output["failure"]["message"]
701            .as_str()
702            .unwrap()
703            .contains("[truncated"));
704    }
705
706    #[test]
707    fn payload_reference_survives_final_render_without_restoring_envelope() {
708        let mut body = json!({"failure":{"message":"x".repeat(3*1024*1024),"type":"T","details":{"codec":"avro","blob":"valid-inline-before-upload"}}});
709        let mut prepared =
710            Prepared::new(&mut body, "/worker/activity-tasks/task/fail", REQUEST_BYTES)
711                .unwrap()
712                .unwrap();
713        let reference = json!({"codec":"avro","external_payload":{"schema":crate::runtime_payloads::SCHEMA,"codec":"avro","reference_id":"ep_01ARZ3NDEKTSV4RRFFQ69G5FAV","sha256":"a".repeat(64),"size_bytes":10}});
714        crate::runtime_payloads::Reference::parse(&reference)
715            .unwrap()
716            .unwrap();
717        body["failure"]["details"] = reference.clone();
718        let bytes = prepared.encode(&mut body, 4096).unwrap();
719        assert_eq!(body["failure"]["details"], reference);
720        assert_eq!(
721            body["failure"]["diagnostics"][MARKER_KEY]["original_message_bytes"],
722            3 * 1024 * 1024
723        );
724        assert!(bytes.len() <= 4096);
725    }
726
727    #[test]
728    fn terminal_workflow_duplicate_and_plain_messages_fit_actual_body() {
729        for structured in [false, true] {
730            let mut command = json!({"type":"fail_workflow","message":"\u{0000}".repeat(3*1024*1024),
731                "exception_type":"Original","non_retryable":true,"failed_activity_execution_id":"exact-logical-id","failed_step_sequence":7});
732            if structured {
733                command["exception"] = json!({"type":"Original","message":command["message"],"non_retryable":true,"details":null});
734            }
735            let mut body =
736                json!({"lease_owner":"exact-owner","workflow_task_attempt":9,"commands":[command]});
737            let mut prepared =
738                Prepared::new(&mut body, "/worker/workflow-tasks/task/complete", 4096)
739                    .unwrap()
740                    .unwrap();
741            let bytes = prepared.encode(&mut body, 4096).unwrap();
742            assert!(bytes.len() <= 4096);
743            assert_eq!(body["lease_owner"], "exact-owner");
744            assert_eq!(body["workflow_task_attempt"], 9);
745            assert_eq!(
746                body["commands"][0]["failed_activity_execution_id"],
747                "exact-logical-id"
748            );
749            assert_eq!(body["commands"][0]["non_retryable"], true);
750            if structured {
751                assert_eq!(
752                    body["commands"][0]["message"],
753                    body["commands"][0]["exception"]["message"]
754                );
755            }
756        }
757    }
758
759    #[test]
760    fn local_attempt_messages_fit_before_observation_without_mutating_prior_commands() {
761        let original = "\u{0000}界🦀".repeat(400_000);
762        let mut attempts = Vec::new();
763        let mut messages = Vec::new();
764        for index in 0..100 {
765            attempts.push(json!({"attempt_number":index+1,"outcome":"failed","message":"temporary","exception_type":"Original","non_retryable":false,"backoff_seconds":17}));
766            messages.push((index, LocalText::new(&original)));
767        }
768        let prior = json!({"type":"record_local_activity","message":"already observed","attempts":[{"message":"already observed"}]});
769        let mut body = json!({"lease_owner":"exact","commands":[prior.clone(),{"type":"record_local_activity","message":"terminal","attempts":attempts}]});
770        fit_local(&mut body, 1, &messages, REQUEST_BYTES).unwrap();
771        assert_eq!(body["commands"][0], prior);
772        assert_eq!(
773            body["commands"][1]["message"],
774            body["commands"][1]["attempts"][99]["message"]
775        );
776        assert!(body["commands"][1]["message"]
777            .as_str()
778            .unwrap()
779            .contains(&format!("original message {}", original.len())));
780        let sum: usize = body["commands"][1]["attempts"]
781            .as_array()
782            .unwrap()
783            .iter()
784            .map(|a| encoded_size(&a["message"]).unwrap() + 1)
785            .sum();
786        assert!(sum + 2 <= DIAGNOSTIC_BYTES);
787        assert!(encoded_size(&body).unwrap() <= REQUEST_BYTES);
788        assert_eq!(body["commands"][1]["attempts"][0]["backoff_seconds"], 17);
789        let before = body.clone();
790        let mut prepared = Prepared::new(
791            &mut body,
792            "/worker/workflow-tasks/task/complete",
793            REQUEST_BYTES,
794        )
795        .unwrap()
796        .unwrap();
797        prepared.encode(&mut body, REQUEST_BYTES).unwrap();
798        assert_eq!(
799            body, before,
800            "transport cannot rewrite observed local messages"
801        );
802        body["lease_owner"] = json!("x".repeat(4096));
803        assert!(matches!(
804            fit_local(&mut body, 1, &messages, 4096),
805            Err(crate::Error::FailureReporting(_))
806        ));
807        assert_eq!(body["commands"][0], prior);
808    }
809
810    #[test]
811    fn local_observation_matches_php_trim_without_changing_small_wire_message() {
812        let message = "\0\t \r\n\u{000b} original \0\t\r\n";
813        assert_eq!(committed_message(message), "original");
814        assert_eq!(
815            committed_message("\u{00a0}original\u{00a0}"),
816            "\u{00a0}original\u{00a0}"
817        );
818        let mut body = json!({"commands":[{"type":"record_local_activity","message":message,"attempts":[{"message":message}]}]});
819        let before = body.clone();
820        fit_local(&mut body, 0, &[(0, LocalText::new(message))], REQUEST_BYTES).unwrap();
821        assert_eq!(body, before);
822        assert!(fit_local(&mut body, 0, &[(0, LocalText::new("\0 \t"))], REQUEST_BYTES).is_err());
823    }
824}