From 34fb7e788da88ba296f11dbcac1a06957c97e739 Mon Sep 17 00:00:00 2001 From: Copilot Date: Fri, 7 Aug 2026 16:58:47 +0000 Subject: [PATCH] Fix AI Guard message truncation to keep newest messages instead of oldest The truncate_messages method in Evaluation used Array#first(max_length), which kept the oldest messages and dropped the newest ones when the message count exceeded max_messages_length. This contradicted the documented behavior ('Older messages are omitted once the message limit is reached') and caused the messages recorded on the ai_guard span's metastruct tag to show stale context instead of the most recent conversation turns. This only affected the messages surfaced in the span for observability; the full, untruncated message list was still sent to the AI Guard evaluation API, so evaluation decisions were unaffected. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lib/datadog/ai_guard/evaluation.rb | 2 +- spec/datadog/ai_guard/evaluation_spec.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/datadog/ai_guard/evaluation.rb b/lib/datadog/ai_guard/evaluation.rb index 844d51a1b0..435684183f 100644 --- a/lib/datadog/ai_guard/evaluation.rb +++ b/lib/datadog/ai_guard/evaluation.rb @@ -74,7 +74,7 @@ def perform_no_op def truncate_messages(serialized_messages) max_length = Datadog.configuration.ai_guard.max_messages_length - serialized_messages.first(max_length) + serialized_messages.last(max_length) end # Truncates content in serialized messages to stay within the configured byte limit. diff --git a/spec/datadog/ai_guard/evaluation_spec.rb b/spec/datadog/ai_guard/evaluation_spec.rb index 58f55c7961..c3c9dfca8b 100644 --- a/spec/datadog/ai_guard/evaluation_spec.rb +++ b/spec/datadog/ai_guard/evaluation_spec.rb @@ -213,8 +213,8 @@ ]) expect(ai_guard_span.get_metastruct_tag("ai_guard").fetch(:messages)).to eq([ - {content: "System prompt", role: :system}, {content: "User message", role: :user}, + {content: "Assistant reply", role: :assistant}, ]) end