Skip to content

Fix AI Guard message truncation to keep newest messages - #3

Open
Copilot wants to merge 1 commit into
masterfrom
copilot/fix-ai-guard-message-truncation-order
Open

Fix AI Guard message truncation to keep newest messages#3
Copilot wants to merge 1 commit into
masterfrom
copilot/fix-ai-guard-message-truncation-order

Conversation

Copilot AI commented Aug 7, 2026

Copy link
Copy Markdown

What does this PR do?
Fixes truncate_messages in lib/datadog/ai_guard/evaluation.rb so that when the number of messages exceeds max_messages_length, the newest messages are kept and the oldest are dropped, instead of the other way around.

Motivation:
Users reported that AI Guard keeps the oldest messages and drops the newest ones once the message limit is hit. The bug was serialized_messages.first(max_length), which keeps the oldest n messages. This contradicts the documented behavior in configuration.rb: "Older messages are omitted once the message limit is reached." Swapped to .last(max_length) to match the documented/intended behavior.

Note: this only affects the messages field recorded on the ai_guard span's metastruct tag (used for observability in the trace UI). The full, untruncated message list is still sent to the AI Guard evaluation API, so evaluation decisions were never affected by this bug.

Change log entry
Yes. Fixed AI Guard to retain the most recent messages (instead of the oldest) when truncating messages recorded in the trace once max_messages_length is exceeded.

Additional Notes:
Generated with AI assistance; the change and tests were reviewed before submission.

How to test the change?
Updated the existing spec in spec/datadog/ai_guard/evaluation_spec.rb ("truncates metastruct messages to max_messages_length") which previously asserted the buggy behavior (keeping the oldest messages); it now asserts the newest messages are retained. Ran:

bundle exec rake test:ai_guard:main

125 examples, 0 failures.

…dest

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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant