Skip to content

fix SQL query to fetch latest messages instead of earliest#1013

Merged
omeraplak merged 6 commits intoVoltAgent:mainfrom
fengyun99:fix_message_sql
Feb 4, 2026
Merged

fix SQL query to fetch latest messages instead of earliest#1013
omeraplak merged 6 commits intoVoltAgent:mainfrom
fengyun99:fix_message_sql

Conversation

@fengyun99
Copy link
Contributor

@fengyun99 fengyun99 commented Feb 3, 2026

PR Checklist

Please check if your PR fulfills the following requirements:

Bugs / Features

What is the current behavior?

When contextLimit is set to 2, the system incorrectly retrieves the oldest two messages from the conversation history instead of the most recent two. This causes the model to miss relevant context from the latest interactions.

For example, with the following sequence:

  1. "hello, my name is tomoni"
  2. "i like play game, recommand me some game"
  3. "What is my name, and what I like to do"

The model correctly recalls the user's name (from message #1) but fails to recall the user's interest in games (from message #2), because only messages #1 and #2 are fetched—but due to incorrect SQL ordering, it actually fetches messages #1 and #2 as the first two, not the last two before the current query. In effect, when the third message arrives, the retrieved context should be messages #1 (the earliest message), but due to wrong sort order (ASC instead of DESC), it returns outdated or misordered context.

What is the new behavior?

The SQL query used to fetch conversation history now correctly orders messages by timestamp in descending order and limits to the most recent contextLimit entries before the current message. This ensures that the model receives the latest relevant context.

Now, in the above example, the third query will correctly receive the second messages (in proper recency order), allowing the model to answer “what I like to do” not "What is my name"

fixes (issue)

Notes for reviewers

The fix involves updating the ORDER BY clause in the SQL query used by memory adapters to sort by timestamp in DESC order before applying LIMIT.

Verified locally with SQLite and PostgreSQL adapters using the provided test sequence.

Note: The D1 and Supabase database adapters have been updated with the corrected query logic, but have not been manually tested due to environment constraints. The change is syntactically consistent with other adapters and follows the same pattern, so it should work as expected—but extra attention during review or CI validation is appreciated.


Summary by cubic

Fixes message fetching to return the most recent messages instead of the earliest, so contextLimit provides the latest context before the current message. Applies to Cloudflare D1, libsql, Postgres, and Supabase while keeping chronological output.

  • Bug Fixes

    • Use ORDER BY created_at DESC with LIMIT in a subquery, then re-order ASC for response.
    • Updated adapters: Cloudflare D1, libsql, Postgres; Supabase orders DESC and reverses results.
    • Keeps roles, before, and after filters working as expected.
  • Migration

    • Behavior change: context limits now return the latest messages; update tests or expectations that assumed oldest.
    • No schema changes.

Written for commit b98f802. Summary will update on new commits.

Summary by CodeRabbit

  • Bug Fixes

    • Revised message retrieval so recent messages are selected before final ordering — conversation lists now present messages in an updated chronological sequence (addresses inconsistent ordering across adapters).
  • Chores

    • Minor version bumps for database adapter packages.

@changeset-bot
Copy link

changeset-bot bot commented Feb 3, 2026

🦋 Changeset detected

Latest commit: b98f802

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@voltagent/cloudflare-d1 Minor
@voltagent/postgres Minor
@voltagent/supabase Minor
@voltagent/libsql Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 3, 2026

📝 Walkthrough

Walkthrough

This pull request changes message retrieval SQL across four database adapter packages to return recent messages: three packages wrap the inner SELECT in a subquery (inner ORDER BY created_at DESC, outer ORDER BY created_at ASC) and Supabase queries DESC then reverses the result array. A changeset marks the four packages for minor version bumps.

Changes

Cohort / File(s) Summary
Changeset Declaration
\.changeset/icy-heads-invent.md
Adds a changeset marking minor version bumps for @voltagent/cloudflare-d1, @voltagent/postgres, @voltagent/supabase, and @voltagent/libsql.
Subquery-Based Ordering Pattern
packages/cloudflare-d1/src/memory-adapter.ts, packages/postgres/src/memory-adapter.ts, packages/libsql/src/memory-core.ts
getMessages SQL now wraps the SELECT in a derived table: inner query ordered created_at DESC, outer query ordered created_at ASC. Alters how LIMIT and ordering interact when selecting recent messages.
Array Reversal Approach (Supabase)
packages/supabase/src/memory-adapter.ts
getMessages now queries with created_at DESC and reverses the returned rows array before mapping to UIMessage objects, achieving the intended final ordering.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nibbled through the SQL vine,
Flipped the rows to newest fine,
Subqueries tucked, arrays reversed,
Four packages hopped and rehearsed,
A tiny rabbit stamps—version minor, all aligned!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and clearly describes the main change: fixing SQL queries to fetch latest messages instead of earliest.
Description check ✅ Passed The description covers the bug, new behavior, notes for reviewers, and includes a changeset entry, though it lacks a specific linked issue number and test confirmation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Important

Action Needed: IP Allowlist Update

If your organization protects your Git platform with IP whitelisting, please add the new CodeRabbit IP address to your allowlist:

  • 136.113.208.247/32 (new)
  • 34.170.211.100/32
  • 35.222.179.152/32

Failure to add the new IP will result in interrupted reviews.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@fengyun99
Copy link
Contributor Author

{NAOB5ONW%8$9W$(0KZ)VPN 95@TI)B~%Y5S KKV7A 6%PH 9B6@ 864))90MJ_C7H~ZYNE

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 5 files

@omeraplak
Copy link
Member

hey @fengyun99 , thank you so much. Can you fix the supabase test?

@omeraplak omeraplak merged commit a35626a into VoltAgent:main Feb 4, 2026
21 of 22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants