fix(cloudflare-d1): keep insertion order for messages that share a timestamp
PR Checklist
- The commit message follows our guidelines
Bugs / Features
- Related issue(s) linked (none filed; repro below)
- Tests for the changes have been added
- Docs have been added / updated (no API change)
- Changesets have been added
What is the current behavior?
D1MemoryAdapter.addMessages() writes one created_at for every message in the batch, and getMessages() orders by created_at only. When rows tie, SQLite keeps scan order, so the ORDER BY created_at DESC LIMIT n step takes the oldest messages of the newest batch.
Repro with @voltagent/cloudflare-d1@2.1.2 on a Miniflare D1 binding, after saving one 4-message turn (user, assistant, tool result, assistant) with addMessages:
getMessages() -> 1 2 3 4
getMessages({ limit: 2 }) -> 1 2 (expected 3 4)
So an agent that loads its last N messages can miss the latest answer of the last turn.
What is the new behavior?
Ties are broken by insertion order: the inner query orders by created_at DESC, rowid DESC, and the outer one by created_at ASC and that rowid. getMessages({ limit: 2 }) now returns 3 and 4. Upserts (ON CONFLICT ... DO UPDATE) keep their rowid, so an updated message keeps its place.
Notes for reviewers
- New
memory-adapter.sqlite.spec.tsruns the adapter against an in-memory SQLite database (node:sqlite) through a small D1 stand-in, so the real SQL runs. Thelimittest fails onmainand passes here. vitest run --typecheck packages/cloudflare-d1(3 passed) andbiome check packages/cloudflare-d1are clean.- The LibSQL and Postgres adapters use the same single-timestamp batch and
ORDER BY created_at; I left them alone to keep this PR to one package, happy to follow up if you want the same change there. - Written with Claude Code; I reviewed the change and ran the checks.
🤖 Generated with Claude Code
Summary by cubic
Fixes message ordering in D1MemoryAdapter.getMessages() so that when messages saved in one batch share a single created_at, the newest messages are returned instead of the oldest when a limit is applied.
Previously, calling getMessages({ limit: 2 }) after saving a 4-message turn returned messages 1 and 2 instead of 3 and 4, which could make an agent miss the latest answer of its last turn. Ties are now broken by rowid (insertion order), and upserts keep their rowid so an updated message keeps its place.
- Adds a spec that runs the adapter's real SQL against an in-memory SQLite database, backed by
@libsql/clientso it runs on Node 20; thelimittest fails onmainand passes here. - Adds a changeset marking this as a patch for
@voltagent/cloudflare-d1. - The LibSQL and Postgres adapters use the same single-timestamp pattern and were left unchanged; the same fix can be applied there as a follow-up.
Summary by CodeRabbit
- Bug Fixes
- Messages with matching timestamps are returned in insertion order. When a limit is applied, the most recently inserted messages are selected consistently.