1use crate::{json, Result, Value};
3use serde::Serialize;
4use serde_json::Map;
5use std::io::{self, Write};
6use thiserror::Error as ThisError;
7
8pub 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#[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
65#[cfg(test)]
66fn metadata_size(value: &Map<String, Value>) -> Result<usize> {
67 metadata_size_with_message(value, false)
68}
69
70fn metadata_size_with_message(value: &Map<String, Value>, include_message: bool) -> Result<usize> {
71 let metadata: Map<_, _> = value
72 .iter()
73 .filter(|(key, _)| !core(key) || (include_message && key.as_str() == "message"))
74 .map(|(key, value)| (key.clone(), value.clone()))
75 .collect();
76 encoded_size(&metadata)
77}
78
79#[derive(Debug)]
82pub(super) struct LocalText {
83 prefix: String,
84 original_bytes: usize,
85}
86impl LocalText {
87 pub(super) fn new(message: &str) -> Self {
88 Self {
89 prefix: prefix(message, MESSAGE_BYTES).to_owned(),
90 original_bytes: message.len(),
91 }
92 }
93 pub(super) fn render(&self, limit: usize) -> String {
94 let marker = format!(
95 "\n[truncated: original message {} UTF-8 bytes]",
96 self.original_bytes
97 );
98 clipped(&self.prefix, limit, &marker, self.original_bytes > limit)
99 }
100}
101
102pub(super) fn committed_message(message: &str) -> &str {
105 message.trim_matches(|ch| matches!(ch, '\0' | '\t' | '\n' | '\r' | '\u{000b}' | ' '))
106}
107
108pub(super) fn fit_local(
111 body: &mut Value,
112 index: usize,
113 messages: &[(usize, LocalText)],
114 limit: usize,
115) -> Result<()> {
116 if messages.is_empty() {
117 return Ok(());
118 }
119 let limit = limit.min(REQUEST_BYTES);
120 let mut target = MESSAGE_BYTES;
121 loop {
122 let command = &mut body["commands"][index];
123 let mut diagnostic_bytes = 2_usize;
124 for (attempt, original) in messages {
125 let message = original.render(target);
126 if committed_message(&message).is_empty() {
127 return Err(FailureReportError::InvalidReport(
128 "local failure message is empty after Server normalization",
129 )
130 .into());
131 }
132 diagnostic_bytes = diagnostic_bytes
133 .saturating_add(encoded_size(&message)?)
134 .saturating_add(1);
135 command["attempts"][*attempt]["message"] = json!(message);
136 }
137 if command.get("message").is_some() {
138 if let Some((attempt, _)) = messages.last() {
139 command["message"] = command["attempts"][*attempt]["message"].clone();
140 }
141 }
142 let size = encoded_size(body)?;
143 if size <= limit && diagnostic_bytes <= DIAGNOSTIC_BYTES {
144 return Ok(());
145 }
146 if target <= 128 {
147 return Err(FailureReportError::RequiredFieldsTooLarge {
148 encoded_bytes: size,
149 limit,
150 }
151 .into());
152 }
153 target = (target / 2).max(128);
154 }
155}
156
157fn core(key: &str) -> bool {
158 matches!(
159 key,
160 "message"
161 | "stack_trace"
162 | "type"
163 | "class"
164 | "non_retryable"
165 | "retryable"
166 | "kind"
167 | "reason"
168 | "sequence"
169 | "timeout_type"
170 | "cancelled"
171 | "malformed_output"
172 )
173}
174
175#[derive(Clone, Copy)]
176struct Budget {
177 message: usize,
178 stack: usize,
179 metadata: usize,
180 names: usize,
181}
182impl Default for Budget {
183 fn default() -> Self {
184 Self {
185 message: MESSAGE_BYTES,
186 stack: STACK_BYTES,
187 metadata: DIAGNOSTIC_BYTES,
188 names: 32,
189 }
190 }
191}
192impl Budget {
193 fn shrink(&mut self) -> bool {
194 if self.stack > 0 {
195 self.stack /= 2;
196 return true;
197 }
198 if self.message > 64 {
199 self.message = (self.message / 2).max(64);
200 return true;
201 }
202 if self.metadata > MARKER_RESERVE {
203 self.metadata = (self.metadata / 2).max(MARKER_RESERVE);
204 return true;
205 }
206 if self.names > 0 {
207 self.names /= 2;
208 return true;
209 }
210 false
211 }
212}
213
214struct Omitted {
215 count: usize,
216 names: Vec<String>,
217 maximum: usize,
218}
219impl Omitted {
220 fn new(maximum: usize) -> Self {
221 Self {
222 count: 0,
223 names: Vec::new(),
224 maximum,
225 }
226 }
227 fn add(&mut self, name: &str) -> Result<()> {
228 self.count = self.count.saturating_add(1);
229 if self.names.len() < self.maximum {
230 self.names.push(prefix(name, 128).to_owned());
231 if encoded_size(&self.names)? > 4096 {
232 self.names.pop();
233 }
234 }
235 Ok(())
236 }
237}
238
239struct Failure {
240 pointer: String,
241 original: Map<String, Value>,
242 metadata_bytes: usize,
243 field_sizes: Vec<usize>,
244 inline_diagnostics: bool,
245 fallback: Option<(String, String)>,
246}
247impl Failure {
248 fn take(
249 body: &mut Value,
250 pointer: String,
251 limit: usize,
252 inline_diagnostics: bool,
253 fallback_pointer: Option<String>,
254 ) -> Result<Self> {
255 let fallback = if let Some(pointer) = fallback_pointer {
256 let value = body
257 .pointer_mut(&pointer)
258 .ok_or(FailureReportError::InvalidReport(
259 "missing fallback message",
260 ))?
261 .take();
262 let Value::String(message) = value else {
263 return Err(
264 FailureReportError::InvalidReport("fallback message must be a string").into(),
265 );
266 };
267 Some((pointer, message))
268 } else {
269 None
270 };
271 let value = body
272 .pointer_mut(&pointer)
273 .ok_or(FailureReportError::InvalidReport("missing failure object"))?
274 .take();
275 let Value::Object(original) = value else {
276 return Err(FailureReportError::InvalidReport("failure must be an object").into());
277 };
278 if fallback.is_none() && !original.get("message").is_some_and(Value::is_string) {
279 return Err(
280 FailureReportError::InvalidReport("failure.message must be a string").into(),
281 );
282 }
283 if original
284 .get("stack_trace")
285 .is_some_and(|v| !v.is_null() && !v.is_string())
286 {
287 return Err(FailureReportError::InvalidReport(
288 "failure.stack_trace must be a string or null",
289 )
290 .into());
291 }
292 let mut metadata_bytes = 2_usize;
293 let mut metadata_fields = 0_usize;
294 let mut field_sizes = Vec::new();
295 let mut required_bytes = 2_usize;
296 for (key, value) in &original {
297 let size = encoded_size(key)?
298 .saturating_add(encoded_size(value)?)
299 .saturating_add(1);
300 field_sizes.push(size);
301 if core(key)
302 && !matches!(key.as_str(), "message" | "stack_trace")
303 && encoded_size(value)? > limit
304 {
305 return Err(FailureReportError::RequiredFieldsTooLarge {
306 encoded_bytes: encoded_size(value)?,
307 limit,
308 }
309 .into());
310 }
311 if core(key) && !matches!(key.as_str(), "message" | "stack_trace") {
312 required_bytes = required_bytes.saturating_add(size).saturating_add(1);
313 }
314 if !core(key) || (fallback.is_some() && key == "message") {
315 metadata_bytes = metadata_bytes
316 .saturating_add(size)
317 .saturating_add(usize::from(metadata_fields > 0));
318 metadata_fields += 1;
319 }
320 }
321 if required_bytes > limit {
322 return Err(FailureReportError::RequiredFieldsTooLarge {
323 encoded_bytes: required_bytes,
324 limit,
325 }
326 .into());
327 }
328 Ok(Self {
329 pointer,
330 original,
331 metadata_bytes,
332 field_sizes,
333 inline_diagnostics,
334 fallback,
335 })
336 }
337
338 fn bounded_fields(&self, budget: Budget) -> Result<(Map<String, Value>, Omitted)> {
339 let mut omitted = Omitted::new(budget.names);
340 let mut output = Map::new();
341 let mut used = 2_usize;
342 let metadata_limit = budget.metadata.saturating_sub(MARKER_RESERVE);
343 for (index, (key, value)) in self.original.iter().enumerate() {
344 if key == "stack_trace" || (key == "message" && self.fallback.is_none()) {
345 continue;
346 }
347 if core(key) && !(key == "message" && self.fallback.is_some()) {
348 output.insert(key.clone(), value.clone());
349 continue;
350 }
351 let size = self.field_sizes[index].saturating_add(1);
352 if used.saturating_add(size) <= metadata_limit {
353 used += size;
354 output.insert(key.clone(), value.clone());
355 } else {
356 omitted.add(key)?;
357 }
358 }
359 Ok((output, omitted))
360 }
361
362 fn render(&self, budget: Budget) -> Result<(Value, Option<Value>)> {
363 let message = self
364 .fallback
365 .as_ref()
366 .map(|(_, message)| message.as_str())
367 .unwrap_or_else(|| {
368 self.original["message"]
369 .as_str()
370 .expect("validated failure message")
371 });
372 let stack = self.original.get("stack_trace").and_then(Value::as_str);
373 let truncated = message.len() > budget.message
374 || stack.is_some_and(|s| budget.stack == 0 || s.len() > budget.stack)
375 || self.metadata_bytes > budget.metadata;
376 if !truncated {
379 return Ok((
380 Value::Object(self.original.clone()),
381 self.fallback.as_ref().map(|_| json!(message)),
382 ));
383 }
384 let (mut output, mut omitted) = self.bounded_fields(budget)?;
385 if let Some(stack) = stack {
386 let marker = format!(
387 "\n[truncated: original stack_trace {} UTF-8 bytes]",
388 stack.len()
389 );
390 if budget.stack == 0 || (stack.len() > budget.stack && budget.stack < marker.len()) {
391 omitted.add("stack_trace")?;
392 } else {
393 output.insert(
394 "stack_trace".into(),
395 Value::String(clipped(stack, budget.stack, &marker, false)),
396 );
397 }
398 } else if let Some(value) = self.original.get("stack_trace") {
399 output.insert("stack_trace".into(), value.clone());
400 }
401 let mut message_marker = MESSAGE_MARKER.to_owned();
402 if truncated && self.inline_diagnostics {
403 message_marker = format!(
406 "\n[truncated: {}]",
407 serde_json::to_string(&json!({
408 "original_message_bytes":message.len(),"original_stack_trace_bytes":stack.map_or(0,str::len),
409 "original_metadata_json_bytes":self.metadata_bytes,"omitted_fields":omitted.names,"omitted_field_count":omitted.count,
410 }))?
411 );
412 } else if truncated {
413 let diagnostic = output.remove("diagnostics");
414 let mut diagnostics = match diagnostic {
415 Some(Value::Object(map)) => map,
416 Some(Value::Null) | None => Map::new(),
417 Some(other) => Map::from_iter([("original".into(), other)]),
418 };
419 if diagnostics.remove(MARKER_KEY).is_some() {
420 omitted.add("diagnostics.sdk_failure_truncation")?;
421 }
422 diagnostics.insert(
423 MARKER_KEY.into(),
424 json!({
425 "original_message_bytes": message.len(),
426 "original_stack_trace_bytes": stack.map_or(0,str::len),
427 "original_metadata_json_bytes": self.metadata_bytes,
428 "omitted_fields": omitted.names,
429 "omitted_field_count": omitted.count,
430 }),
431 );
432 output.insert("diagnostics".into(), Value::Object(diagnostics));
433 }
434 let rendered_message =
435 Value::String(clipped(message, budget.message, &message_marker, truncated));
436 let fallback_message = if self.fallback.is_some() {
437 if self.original.contains_key("message") && !output.contains_key("message") {
440 output.insert("message".into(), json!(""));
441 }
442 Some(rendered_message)
443 } else {
444 output.insert("message".into(), rendered_message);
445 None
446 };
447 if metadata_size_with_message(&output, self.fallback.is_some())? > budget.metadata {
450 return Err(FailureReportError::InvalidReport(
451 "truncation diagnostics exceed their serialized budget",
452 )
453 .into());
454 }
455 Ok((Value::Object(output), fallback_message))
456 }
457
458 fn refresh_details(&mut self, body: &Value) -> Result<()> {
459 if let Some(details) = body
460 .pointer(&self.pointer)
461 .and_then(|failure| failure.get("details"))
462 {
463 if self.original.contains_key("details") {
464 self.original.insert("details".into(), details.clone());
465 for (index, (key, value)) in self.original.iter().enumerate() {
466 if key == "details" {
467 self.field_sizes[index] = encoded_size(key)? + 1 + encoded_size(value)?;
468 }
469 }
470 }
471 }
472 Ok(())
473 }
474}
475
476struct MessageMirror {
478 target: String,
479 source: String,
480 original_bytes: usize,
481}
482
483#[derive(Default)]
484struct ReportPositions {
485 pointers: Vec<(String, Option<String>)>,
486 texts: Vec<(String, LocalText)>,
487 mirrors: Vec<MessageMirror>,
488 guarded: bool,
489}
490impl ReportPositions {
491 fn complete(&mut self, body: &Value) {
492 for (index, command) in body["commands"]
493 .as_array()
494 .into_iter()
495 .flatten()
496 .enumerate()
497 {
498 if command["type"] == "fail_workflow" || command["type"] == "fail_update" {
499 self.guarded = true;
500 if command["exception"]["message"]
501 .as_str()
502 .is_some_and(|message| !committed_message(message).is_empty())
503 {
504 self.pointers
505 .push((format!("/commands/{index}/exception"), None));
506 if command.get("message").is_some() {
507 self.mirrors.push(MessageMirror {
508 target: format!("/commands/{index}/message"),
509 source: format!("/commands/{index}/exception/message"),
510 original_bytes: command["message"].as_str().map_or(0, str::len),
511 });
512 }
513 } else if let Some(message) = command["message"].as_str() {
514 if command["exception"].is_object() {
515 self.pointers.push((
516 format!("/commands/{index}/exception"),
517 Some(format!("/commands/{index}/message")),
518 ));
519 } else {
520 self.texts.push((
521 format!("/commands/{index}/message"),
522 LocalText::new(message),
523 ));
524 }
525 }
526 }
527 if command["type"] == "record_local_activity" {
528 self.guarded |= command.get("message").is_some()
529 || command["attempts"]
530 .as_array()
531 .into_iter()
532 .flatten()
533 .any(|v| v.get("message").is_some());
534 }
535 }
536 }
537}
538
539pub(super) struct Prepared {
540 failures: Vec<Failure>,
541 texts: Vec<(String, LocalText)>,
542 mirrors: Vec<MessageMirror>,
543}
544impl Prepared {
545 pub(super) fn new(body: &mut Value, path: &str, limit: usize) -> Result<Option<Self>> {
546 let parts: Vec<_> = path.trim_matches('/').split('/').collect();
547 let mut positions = ReportPositions::default();
548 match parts.as_slice() {
549 ["worker", "activity-tasks" | "workflow-tasks" | "query-tasks", _, "fail"] => {
550 positions.guarded = true;
551 if body["failure"]["message"].is_string() {
554 positions.pointers.push(("/failure".into(), None));
555 }
556 }
557 ["worker", "workflow-tasks", _, "complete"] => {
558 positions.complete(body);
559 }
560 _ => return Ok(None),
561 }
562 let ReportPositions {
563 pointers,
564 texts,
565 mirrors,
566 guarded,
567 } = positions;
568 if pointers.is_empty() && texts.is_empty() && !guarded {
569 return Ok(None);
570 }
571 if path.len() > limit {
572 return Err(FailureReportError::RequiredFieldsTooLarge {
573 encoded_bytes: path.len(),
574 limit,
575 }
576 .into());
577 }
578 let mut failures = Vec::new();
579 let inline_diagnostics = matches!(
580 parts.as_slice(),
581 ["worker", "workflow-tasks" | "query-tasks", _, "fail"]
582 );
583 for (pointer, fallback) in pointers {
584 failures.push(Failure::take(
585 body,
586 pointer,
587 limit,
588 inline_diagnostics,
589 fallback,
590 )?);
591 }
592 let prepared = Self {
593 failures,
594 texts,
595 mirrors,
596 };
597 prepared.render(body, Budget::default())?;
598 Ok(Some(prepared))
599 }
600
601 fn render(&self, body: &mut Value, budget: Budget) -> Result<()> {
602 for failure in &self.failures {
603 let (rendered, fallback_message) = failure.render(budget)?;
604 *body
605 .pointer_mut(&failure.pointer)
606 .expect("retained failure location") = rendered;
607 if let (Some((pointer, _)), Some(message)) = (&failure.fallback, fallback_message) {
608 *body
609 .pointer_mut(pointer)
610 .expect("retained fallback message") = message;
611 }
612 }
613 for (pointer, original) in &self.texts {
614 *body
615 .pointer_mut(pointer)
616 .expect("retained message location") = json!(original.render(budget.message));
617 }
618 for mirror in &self.mirrors {
619 if mirror.original_bytes <= budget.message {
623 continue;
624 }
625 let message = body
626 .pointer(&mirror.source)
627 .expect("retained exception message")
628 .clone();
629 *body
630 .pointer_mut(&mirror.target)
631 .expect("retained command message") = message;
632 }
633 Ok(())
634 }
635
636 pub(super) fn can_reduce(&self) -> bool {
637 !self.failures.is_empty() || !self.texts.is_empty()
638 }
639
640 pub(super) fn encode(&mut self, body: &mut Value, limit: usize) -> Result<Vec<u8>> {
641 let limit = limit.min(REQUEST_BYTES);
642 for failure in &mut self.failures {
645 failure.refresh_details(body)?;
646 }
647 let mut budget = Budget::default();
648 if !self
649 .failures
650 .iter()
651 .any(|f| f.original.get("stack_trace").is_some_and(Value::is_string))
652 {
653 budget.stack = 0;
654 }
655 loop {
656 self.render(body, budget)?;
657 let size = encoded_size(body)?;
658 if size <= limit {
659 let bytes = serde_json::to_vec(body)?;
660 if bytes.len() <= limit {
661 return Ok(bytes);
662 }
663 return Err(FailureReportError::RequiredFieldsTooLarge {
664 encoded_bytes: bytes.len(),
665 limit,
666 }
667 .into());
668 }
669 if (self.failures.is_empty() && self.texts.is_empty()) || !budget.shrink() {
672 return Err(FailureReportError::RequiredFieldsTooLarge {
673 encoded_bytes: size,
674 limit,
675 }
676 .into());
677 }
678 }
679 }
680}
681
682#[cfg(test)]
683mod tests {
684 use super::*;
685 fn encode(mut body: Value, limit: usize) -> (Value, Vec<u8>) {
686 let mut prepared = Prepared::new(&mut body, "/worker/activity-tasks/task/fail", limit)
687 .unwrap()
688 .unwrap();
689 let bytes = prepared.encode(&mut body, limit).unwrap();
690 assert_eq!(serde_json::from_slice::<Value>(&bytes).unwrap(), body);
691 (body, bytes)
692 }
693 #[test]
694 fn small_failure_preserves_type_flags_and_details() {
695 let input = json!({"activity_attempt_id":"attempt", "lease_owner":"owner", "failure":{"type":"Declined","message":"no","non_retryable":true,"details":null}});
696 let (output, bytes) = encode(input.clone(), REQUEST_BYTES);
697 assert_eq!(output, input);
698 assert_eq!(bytes, serde_json::to_vec(&input).unwrap());
699 }
700 #[test]
701 fn unicode_escaping_and_markers_are_included_in_actual_request_cap() {
702 let input = json!({"activity_attempt_id":"attempt", "lease_owner":"owner", "failure":{
703 "type":"Original", "non_retryable":false,"retryable":true,
704 "message":"\u{0000}界🦀".repeat(600_000),"stack_trace":"\u{0001}".repeat(3*1024*1024),
705 "diagnostics":{"causes":{"nested":"x".repeat(3*1024*1024)}}, "arbitrary":"y".repeat(3*1024*1024)}});
706 let (output, bytes) = encode(input, REQUEST_BYTES);
707 assert!(bytes.len() <= REQUEST_BYTES);
708 assert_eq!(output["failure"]["type"], "Original");
709 assert_eq!(output["failure"]["non_retryable"], false);
710 assert_eq!(output["failure"]["retryable"], true);
711 assert!(output["failure"]["message"]
712 .as_str()
713 .unwrap()
714 .contains("[truncated"));
715 assert!(output["failure"]["message"].as_str().unwrap().len() <= MESSAGE_BYTES);
716 assert!(
717 output["failure"]["diagnostics"][MARKER_KEY]["omitted_field_count"]
718 .as_u64()
719 .unwrap()
720 > 0
721 );
722 }
723 #[test]
724 fn lower_known_limit_and_exact_identity_are_preserved() {
725 let (output, bytes) = encode(
726 json!({"activity_attempt_id":"exact-attempt", "lease_owner":"exact-owner", "failure":{"type":"Original","message":"\"\\\n".repeat(1024*1024)}}),
727 4096,
728 );
729 assert!(bytes.len() <= 4096);
730 assert_eq!(output["activity_attempt_id"], "exact-attempt");
731 assert_eq!(output["lease_owner"], "exact-owner");
732 let mut impossible =
733 json!({"lease_owner":"x".repeat(4096),"failure":{"type":"T","message":"short"}});
734 let mut p = Prepared::new(&mut impossible, "/worker/activity-tasks/task/fail", 4096)
735 .unwrap()
736 .unwrap();
737 assert!(matches!(
738 p.encode(&mut impossible, 4096),
739 Err(crate::Error::FailureReporting(
740 FailureReportError::RequiredFieldsTooLarge { .. }
741 ))
742 ));
743 }
744
745 #[test]
746 fn combined_metadata_budget_includes_inserted_escaped_diagnostics() {
747 let details = json!({"codec":"avro","blob":"a".repeat(20_000)});
748 let (output, bytes) = encode(
749 json!({"failure":{
750 "message":"界".repeat(MESSAGE_BYTES),"type":"SameType","non_retryable":true,
751 "details":details,"diagnostics":{"escaped":"\u{0000}".repeat(8000)},
752 "runtime_diagnostics":{"causes":[{"nested":"x".repeat(8000)}]},
753 }}),
754 REQUEST_BYTES,
755 );
756 let failure = output["failure"].as_object().unwrap();
757 assert!(metadata_size(failure).unwrap() <= DIAGNOSTIC_BYTES);
758 assert!(bytes.len() <= REQUEST_BYTES);
759 assert_eq!(failure["type"], "SameType");
760 assert_eq!(failure["non_retryable"], true);
761 if let Some(kept) = failure.get("details") {
762 assert_eq!(kept, &details);
763 }
764 assert!(
765 failure["diagnostics"][MARKER_KEY]["omitted_field_count"]
766 .as_u64()
767 .unwrap()
768 > 0
769 );
770 }
771
772 #[test]
773 fn arbitrary_large_metadata_keys_and_values_cannot_bypass_the_cap() {
774 let mut failure = Map::from_iter([
775 ("message".into(), json!("small")),
776 ("type".into(), json!("Original")),
777 ]);
778 for index in 0..2000 {
779 failure.insert(
780 format!("{index}{}", "\u{0000}".repeat(1000)),
781 json!({"nested":"x".repeat(2000)}),
782 );
783 }
784 let (output, bytes) = encode(json!({"failure":failure}), REQUEST_BYTES);
785 assert!(bytes.len() <= REQUEST_BYTES);
786 assert!(metadata_size(output["failure"].as_object().unwrap()).unwrap() <= DIAGNOSTIC_BYTES);
787 let omitted = output["failure"]["diagnostics"][MARKER_KEY]["omitted_field_count"]
788 .as_u64()
789 .unwrap() as usize;
790 let retained = output["failure"]
791 .as_object()
792 .unwrap()
793 .keys()
794 .filter(|key| !core(key) && key.as_str() != "diagnostics")
795 .count();
796 assert_eq!(omitted + retained, 2000);
797 assert!(output["failure"]["message"]
798 .as_str()
799 .unwrap()
800 .contains("[truncated"));
801 }
802
803 #[test]
804 fn payload_reference_survives_final_render_without_restoring_envelope() {
805 let mut body = json!({"failure":{"message":"x".repeat(3*1024*1024),"type":"T","details":{"codec":"avro","blob":"valid-inline-before-upload"}}});
806 let mut prepared =
807 Prepared::new(&mut body, "/worker/activity-tasks/task/fail", REQUEST_BYTES)
808 .unwrap()
809 .unwrap();
810 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}});
811 crate::runtime_payloads::Reference::parse(&reference)
812 .unwrap()
813 .unwrap();
814 body["failure"]["details"] = reference.clone();
815 let bytes = prepared.encode(&mut body, 4096).unwrap();
816 assert_eq!(body["failure"]["details"], reference);
817 assert_eq!(
818 body["failure"]["diagnostics"][MARKER_KEY]["original_message_bytes"],
819 3 * 1024 * 1024
820 );
821 assert!(bytes.len() <= 4096);
822 }
823
824 #[test]
825 fn terminal_workflow_duplicate_and_plain_messages_fit_actual_body() {
826 for structured in [false, true] {
827 let mut command = json!({"type":"fail_workflow","message":"\u{0000}".repeat(3*1024*1024),
828 "exception_type":"Original","non_retryable":true,"failed_activity_execution_id":"exact-logical-id","failed_step_sequence":7});
829 if structured {
830 command["exception"] = json!({"type":"Original","message":command["message"],"non_retryable":true,"details":null});
831 }
832 let mut body =
833 json!({"lease_owner":"exact-owner","workflow_task_attempt":9,"commands":[command]});
834 let mut prepared =
835 Prepared::new(&mut body, "/worker/workflow-tasks/task/complete", 4096)
836 .unwrap()
837 .unwrap();
838 let bytes = prepared.encode(&mut body, 4096).unwrap();
839 assert!(bytes.len() <= 4096);
840 assert_eq!(body["lease_owner"], "exact-owner");
841 assert_eq!(body["workflow_task_attempt"], 9);
842 assert_eq!(
843 body["commands"][0]["failed_activity_execution_id"],
844 "exact-logical-id"
845 );
846 assert_eq!(body["commands"][0]["non_retryable"], true);
847 if structured {
848 assert_eq!(body["commands"][0]["exception"]["message"], "");
849 assert!(body["commands"][0]["message"]
850 .as_str()
851 .unwrap()
852 .contains("[truncated"));
853 assert!(body["commands"][0]["exception"]["diagnostics"][MARKER_KEY]
854 ["omitted_fields"]
855 .as_array()
856 .unwrap()
857 .iter()
858 .any(|v| v == "message"));
859 }
860 }
861 }
862
863 #[test]
864 fn nonblank_nested_message_and_redundant_outer_copy_fit_after_escaping() {
865 let original = "\u{0000}界🦀".repeat(400_000);
866 let mut body = json!({"lease_owner":"owner","commands":[{"type":"fail_workflow","message":original,
867 "exception":{"type":"Original","message":original,"stack_trace":"\u{0001}".repeat(3*1024*1024)}}]});
868 let mut report = Prepared::new(&mut body, "/worker/workflow-tasks/task/complete", 4096)
869 .unwrap()
870 .unwrap();
871 let bytes = report.encode(&mut body, 4096).unwrap();
872 assert!(bytes.len() <= 4096);
873 assert_eq!(
874 body["commands"][0]["message"],
875 body["commands"][0]["exception"]["message"]
876 );
877 assert!(body["commands"][0]["message"]
878 .as_str()
879 .unwrap()
880 .contains("[truncated"));
881 }
882
883 #[test]
884 fn local_attempt_messages_fit_before_observation_without_mutating_prior_commands() {
885 let original = "\u{0000}界🦀".repeat(400_000);
886 let mut attempts = Vec::new();
887 let mut messages = Vec::new();
888 for index in 0..100 {
889 attempts.push(json!({"attempt_number":index+1,"outcome":"failed","message":"temporary","exception_type":"Original","non_retryable":false,"backoff_seconds":17}));
890 messages.push((index, LocalText::new(&original)));
891 }
892 let prior = json!({"type":"record_local_activity","message":"already observed","attempts":[{"message":"already observed"}]});
893 let mut body = json!({"lease_owner":"exact","commands":[prior.clone(),{"type":"record_local_activity","message":"terminal","attempts":attempts}]});
894 fit_local(&mut body, 1, &messages, REQUEST_BYTES).unwrap();
895 assert_eq!(body["commands"][0], prior);
896 assert_eq!(
897 body["commands"][1]["message"],
898 body["commands"][1]["attempts"][99]["message"]
899 );
900 assert!(body["commands"][1]["message"]
901 .as_str()
902 .unwrap()
903 .contains(&format!("original message {}", original.len())));
904 let sum: usize = body["commands"][1]["attempts"]
905 .as_array()
906 .unwrap()
907 .iter()
908 .map(|a| encoded_size(&a["message"]).unwrap() + 1)
909 .sum();
910 assert!(sum + 2 <= DIAGNOSTIC_BYTES);
911 assert!(encoded_size(&body).unwrap() <= REQUEST_BYTES);
912 assert_eq!(body["commands"][1]["attempts"][0]["backoff_seconds"], 17);
913 let before = body.clone();
914 let mut prepared = Prepared::new(
915 &mut body,
916 "/worker/workflow-tasks/task/complete",
917 REQUEST_BYTES,
918 )
919 .unwrap()
920 .unwrap();
921 prepared.encode(&mut body, REQUEST_BYTES).unwrap();
922 assert_eq!(
923 body, before,
924 "transport cannot rewrite observed local messages"
925 );
926 body["lease_owner"] = json!("x".repeat(4096));
927 assert!(matches!(
928 fit_local(&mut body, 1, &messages, 4096),
929 Err(crate::Error::FailureReporting(_))
930 ));
931 assert_eq!(body["commands"][0], prior);
932 }
933
934 #[test]
935 fn local_observation_matches_php_trim_without_changing_small_wire_message() {
936 let message = "\0\t \r\n\u{000b} original \0\t\r\n";
937 assert_eq!(committed_message(message), "original");
938 assert_eq!(
939 committed_message("\u{00a0}original\u{00a0}"),
940 "\u{00a0}original\u{00a0}"
941 );
942 let mut body = json!({"commands":[{"type":"record_local_activity","message":message,"attempts":[{"message":message}]}]});
943 let before = body.clone();
944 fit_local(&mut body, 0, &[(0, LocalText::new(message))], REQUEST_BYTES).unwrap();
945 assert_eq!(body, before);
946 assert!(fit_local(&mut body, 0, &[(0, LocalText::new("\0 \t"))], REQUEST_BYTES).is_err());
947 }
948}