Implement paginated queries for the local agent message board (#46978)

## What changed

Implement `AgentMessageBoard` for `LocalAgentMessageBoard`, adding SQLite queries to list channels and threads, search posts, and read thread replies.

- Support Unicode case-insensitive substring search and post filters for channel, author, and `after_message_id`.
- Sort threads by creation time or latest activity, with reply counts and previews of the root post and latest reply.
- Bound pages to 50 results and post previews to a shared 20,000-character response budget. Use offset cursors for pagination; concurrent posts may shift results between pages.
- Add indexes for board and thread timestamp queries.

## Testing

Add integration tests covering pagination, page and preview caps, Unicode search and truncation, thread activity ordering, filtered search, and rejection of non-root thread IDs and unknown callers.

GitOrigin-RevId: c9c673768596efb6d33160e2db8dff62ee9b9cdb
This commit is contained in:
jif
2026-09-21 09:00:44 +00:00
committed by copyberry
parent 293de27177
commit 8f2c15c398
6 changed files with 709 additions and 2 deletions
+1
View File
@@ -2099,6 +2099,7 @@ dependencies = [
name = "codex-agent-message-board-extension"
version = "0.0.0"
dependencies = [
"base64 0.22.1",
"caseless",
"chrono",
"codex-protocol",
@@ -14,6 +14,7 @@ test = false
workspace = true
[dependencies]
base64 = { workspace = true }
caseless = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
codex-protocol = { workspace = true }
@@ -34,6 +34,9 @@ use std::collections::HashSet;
use std::sync::Arc;
use uuid::Uuid;
mod paging;
mod queries;
const MAX_POST_BYTES: usize = 64 * 1024;
const MAX_CHANNEL_BYTES: usize = 128;
const MAX_READ_CHARS: usize = 20_000;
@@ -52,6 +55,8 @@ CREATE TABLE IF NOT EXISTS posts (
);
CREATE INDEX IF NOT EXISTS posts_board_channel ON posts(board,channel,seq);
CREATE INDEX IF NOT EXISTS posts_board_root ON posts(board,root,seq);
CREATE INDEX IF NOT EXISTS posts_board_root_timestamp ON posts(board,root,timestamp,seq);
CREATE INDEX IF NOT EXISTS posts_board_timestamp ON posts(board,timestamp,seq);
CREATE TABLE IF NOT EXISTS subscriptions (
board TEXT NOT NULL, target TEXT NOT NULL, agent TEXT NOT NULL,
PRIMARY KEY(board,target,agent)
@@ -0,0 +1,86 @@
//! Bounded offset pagination. Concurrent posts may shift results between pages.
//! Cursors belong to the original query; restart without one to refresh the listing.
use super::StoredPost;
use super::invalid;
use super::storage_error;
use crate::Page;
use crate::PageRequest;
use crate::PostPreview;
use crate::SortDirection;
use base64::Engine;
use base64::prelude::BASE64_URL_SAFE_NO_PAD;
use codex_protocol::error::Result;
pub(super) struct Window {
offset: u32,
pub(super) limit: usize,
}
impl Window {
pub(super) fn new(page: &PageRequest) -> Result<Self> {
let offset = match &page.cursor {
Some(cursor) => {
let mut bytes = [0; 4];
let len = BASE64_URL_SAFE_NO_PAD
.decode_slice(cursor, &mut bytes)
.map_err(|_| invalid("invalid cursor"))?;
if len != bytes.len() {
return Err(invalid("invalid cursor"));
}
u32::from_be_bytes(bytes)
}
None => 0,
};
Ok(Self {
offset,
limit: (page.limit.get() as usize).min(50),
})
}
pub(super) fn offset(&self) -> i64 {
i64::from(self.offset)
}
pub(super) fn finish<T>(self, mut results: Vec<T>) -> Result<Page<T>> {
let has_more = results.len() > self.limit;
results.truncate(self.limit);
let next_cursor = if has_more {
let offset = self
.offset
.checked_add(results.len() as u32)
.ok_or_else(|| invalid("cursor offset exceeds the board limit"))?;
Some(BASE64_URL_SAFE_NO_PAD.encode(offset.to_be_bytes()))
} else {
None
};
Ok(Page {
results,
next_cursor,
})
}
}
pub(super) fn direction(direction: SortDirection) -> &'static str {
match direction {
SortDirection::NewestFirst => "DESC",
SortDirection::OldestFirst => "ASC",
}
}
pub(super) fn preview(post: StoredPost, max_chars: usize) -> PostPreview {
let n_chars = post.text.chars().count();
let text_preview = post.text.chars().take(max_chars).collect();
PostPreview {
metadata: post.metadata,
text_preview,
n_chars,
truncated: n_chars > max_chars,
}
}
pub(super) fn decode_posts(rows: Vec<String>) -> Result<Vec<StoredPost>> {
rows.into_iter()
.map(|row| serde_json::from_str(&row).map_err(storage_error))
.collect()
}
@@ -0,0 +1,298 @@
//! Implements the board contract using bounded SQLite queries with ordinary offset pagination.
use super::LocalAgentMessageBoard;
use super::MAX_READ_CHARS;
use super::StoredPost;
use super::invalid;
use super::paging::Window;
use super::paging::decode_posts;
use super::paging::direction;
use super::paging::preview;
use super::storage_error;
use crate::AgentMessageBoard;
use crate::ChannelQuery;
use crate::ChannelSummary;
use crate::CreateChannelRequest;
use crate::Page;
use crate::PostContent;
use crate::PostMetadata;
use crate::PostPreview;
use crate::PostQuery;
use crate::PostRequest;
use crate::ReadPostRequest;
use crate::ReadThreadRequest;
use crate::SubscriptionRequest;
use crate::SubscriptionState;
use crate::ThreadPage;
use crate::ThreadQuery;
use crate::ThreadSort;
use crate::ThreadSummary;
use caseless::default_case_fold_str;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::Result;
use futures::future::BoxFuture;
use sqlx::QueryBuilder;
impl AgentMessageBoard for LocalAgentMessageBoard {
fn identity(&self) -> SessionId {
self.identity
}
fn create_channel(
&self,
caller: ThreadId,
request: CreateChannelRequest,
) -> BoxFuture<'_, Result<ChannelSummary>> {
Box::pin(LocalAgentMessageBoard::create_channel(
self, caller, request,
))
}
fn post(&self, caller: ThreadId, request: PostRequest) -> BoxFuture<'_, Result<PostMetadata>> {
Box::pin(LocalAgentMessageBoard::post(self, caller, request))
}
fn set_subscription(
&self,
caller: ThreadId,
request: SubscriptionRequest,
) -> BoxFuture<'_, Result<SubscriptionState>> {
Box::pin(LocalAgentMessageBoard::set_subscription(
self, caller, request,
))
}
fn read_post(
&self,
caller: ThreadId,
request: ReadPostRequest,
) -> BoxFuture<'_, Result<PostContent>> {
Box::pin(LocalAgentMessageBoard::read_post(self, caller, request))
}
fn list_channels(
&self,
caller: ThreadId,
query: ChannelQuery,
) -> BoxFuture<'_, Result<Page<ChannelSummary>>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let mut tx = self.pool.begin().await.map_err(storage_error)?;
let window = Window::new(&query.page)?;
let order = direction(query.direction);
let mut sql = QueryBuilder::new("SELECT c.name FROM channels c WHERE c.board=");
sql.push_bind(self.identity.to_string())
.push(" AND instr(c.name_search,")
.push_bind(default_case_fold_str(&query.query.unwrap_or_default()))
.push(
")>0 ORDER BY COALESCE(
(SELECT MAX(p.timestamp) FROM posts p WHERE p.board=c.board AND p.channel=c.name),
c.timestamp) ",
)
.push(order)
.push(",c.name ")
.push(order)
.push(" LIMIT ")
.push_bind((window.limit + 1) as i64)
.push(" OFFSET ")
.push_bind(window.offset());
let names = sql
.build_query_scalar::<String>()
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?;
let mut channels = Vec::with_capacity(names.len());
for name in names {
channels.push(self.channel_summary(&mut tx, &name).await?);
}
window.finish(channels)
})
}
fn list_threads(
&self,
caller: ThreadId,
query: ThreadQuery,
) -> BoxFuture<'_, Result<Page<ThreadSummary>>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let mut tx = self.pool.begin().await.map_err(storage_error)?;
let exists: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM channels WHERE board=? AND name=?)",
)
.bind(self.identity.to_string())
.bind(&query.channel_name)
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
if !exists {
return Err(invalid("channel not found in this board"));
}
let window = Window::new(&query.page)?;
let order = direction(query.direction);
let mut sql = QueryBuilder::new("SELECT p.payload FROM posts p WHERE p.board=");
sql.push_bind(self.identity.to_string())
.push(" AND p.channel=")
.push_bind(query.channel_name)
.push(" AND p.id=p.root")
.push(" ORDER BY ");
match query.sort {
ThreadSort::Created => {
sql.push("p.timestamp");
}
ThreadSort::Activity => {
sql.push("(SELECT MAX(r.timestamp) FROM posts r WHERE r.board=p.board AND r.root=p.id)");
}
}
sql.push(" ")
.push(order)
.push(",p.seq ")
.push(order)
.push(" LIMIT ")
.push_bind((window.limit + 1) as i64)
.push(" OFFSET ")
.push_bind(window.offset());
let roots = decode_posts(
sql.build_query_scalar::<String>()
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?,
)?;
let chars = (query.max_chars_per_post.get() as usize)
.min(MAX_READ_CHARS / (2 * roots.len().min(window.limit).max(1)));
let mut threads = Vec::with_capacity(roots.len());
for root in roots {
let id = root.metadata.message_id;
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM posts WHERE board=? AND root=? AND id<>root",
)
.bind(self.identity.to_string())
.bind(id.to_string())
.fetch_one(&mut *tx)
.await
.map_err(storage_error)?;
let last: Option<String> = sqlx::query_scalar(
"SELECT payload FROM posts WHERE board=? AND root=? AND id<>root
ORDER BY timestamp DESC,seq DESC LIMIT 1",
)
.bind(self.identity.to_string())
.bind(id.to_string())
.fetch_optional(&mut *tx)
.await
.map_err(storage_error)?;
let last: Option<StoredPost> = last
.map(|value| serde_json::from_str(&value))
.transpose()
.map_err(storage_error)?;
let activity = last.as_ref().map_or(root.metadata.created_at, |last| {
last.metadata.created_at.max(root.metadata.created_at)
});
threads.push(ThreadSummary {
thread_id: id,
root_post: preview(root, chars),
reply_count: count as usize,
last_activity_at: activity,
latest_reply: last.map(|post| preview(post, chars)),
});
}
window.finish(threads)
})
}
fn search_posts(
&self,
caller: ThreadId,
query: PostQuery,
) -> BoxFuture<'_, Result<Page<PostPreview>>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let mut tx = self.pool.begin().await.map_err(storage_error)?;
let window = Window::new(&query.page)?;
let after = if let Some(id) = query.after_message_id {
Some(
sqlx::query_as::<_, (i64, i64)>(
"SELECT timestamp,seq FROM posts WHERE board=? AND id=?",
)
.bind(self.identity.to_string())
.bind(id.to_string())
.fetch_optional(&mut *tx)
.await
.map_err(storage_error)?
.ok_or_else(|| invalid("post not found in this board"))?,
)
} else {
None
};
let mut sql = QueryBuilder::new("SELECT payload FROM posts WHERE board=");
sql.push_bind(self.identity.to_string());
if let Some(channel) = query.channel_name {
sql.push(" AND channel=").push_bind(channel);
}
if let Some(author) = query.author {
sql.push(" AND author=").push_bind(author.to_string());
}
if let Some(text) = query.query {
sql.push(" AND instr(body_search,")
.push_bind(default_case_fold_str(&text))
.push(")>0");
}
if let Some((timestamp, seq)) = after {
sql.push(" AND (timestamp,seq)>(")
.push_bind(timestamp)
.push(",")
.push_bind(seq)
.push(")");
}
sql.push(" ORDER BY timestamp DESC,seq DESC LIMIT ")
.push_bind((window.limit + 1) as i64)
.push(" OFFSET ")
.push_bind(window.offset());
let posts = decode_posts(
sql.build_query_scalar::<String>()
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?,
)?;
let chars = (query.max_chars_per_post.get() as usize)
.min(MAX_READ_CHARS / posts.len().min(window.limit).max(1));
window.finish(posts.into_iter().map(|post| preview(post, chars)).collect())
})
}
fn read_thread(
&self,
caller: ThreadId,
request: ReadThreadRequest,
) -> BoxFuture<'_, Result<ThreadPage>> {
Box::pin(async move {
self.host.agent_path(caller).await?;
let mut tx = self.pool.begin().await.map_err(storage_error)?;
let root = self.load_post(&mut tx, request.thread_id).await?;
if root.metadata.thread_id != request.thread_id {
return Err(invalid("thread_id must identify a top-level post"));
}
let window = Window::new(&request.page)?;
let posts = decode_posts(
sqlx::query_scalar(
"SELECT payload FROM posts WHERE board=? AND root=? AND id<>root
ORDER BY timestamp DESC,seq DESC LIMIT ? OFFSET ?",
)
.bind(self.identity.to_string())
.bind(request.thread_id.to_string())
.bind((window.limit + 1) as i64)
.bind(window.offset())
.fetch_all(&mut *tx)
.await
.map_err(storage_error)?,
)?;
let chars = (request.max_chars_per_post.get() as usize)
.min(MAX_READ_CHARS / (posts.len().min(window.limit) + 1));
Ok(ThreadPage {
root_post: preview(root, chars),
replies: window
.finish(posts.into_iter().map(|post| preview(post, chars)).collect())?,
})
})
}
}
@@ -5,6 +5,7 @@ use std::num::NonZeroU32;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicI64;
use std::sync::atomic::Ordering;
use chrono::DateTime;
@@ -20,6 +21,7 @@ use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
struct Host {
clock: AtomicI64,
members: HashMap<ThreadId, AgentPath>,
active: AtomicBool,
fail_notifications: AtomicBool,
@@ -46,10 +48,11 @@ impl MessageBoardHost for Host {
}
fn current_time(&self, _caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>> {
Box::pin(async {
Box::pin(async move {
Ok(DateTime::parse_from_rfc3339("2026-09-18T12:00:00Z")
.map_err(|error| CodexErr::Io(std::io::Error::other(error)))?
.with_timezone(&Utc))
.with_timezone(&Utc)
+ chrono::Duration::seconds(self.clock.fetch_add(1, Ordering::SeqCst)))
})
}
@@ -84,6 +87,7 @@ async fn shared_handles_resume_posts_and_preserve_subscription_rules() {
let child = ThreadId::new();
let child_path = AgentPath::root().join("worker").unwrap();
let host = Arc::new(Host {
clock: AtomicI64::default(),
members: [(root, AgentPath::root()), (child, child_path.clone())].into(),
fail_notifications: AtomicBool::new(false),
active: AtomicBool::new(true),
@@ -218,6 +222,7 @@ async fn failed_requests_do_not_create_channels_or_notify_inactive_agents() {
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap());
let root = ThreadId::new();
let host = Arc::new(Host {
clock: AtomicI64::default(),
members: [(root, AgentPath::root())].into(),
fail_notifications: AtomicBool::new(false),
active: AtomicBool::new(false),
@@ -274,3 +279,314 @@ async fn failed_requests_do_not_create_channels_or_notify_inactive_agents() {
}
);
}
#[tokio::test]
async fn queries_enforce_page_and_preview_caps() {
let dir = tempfile::tempdir().unwrap();
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap());
let root = ThreadId::new();
let host = Arc::new(Host {
fail_notifications: AtomicBool::new(false),
clock: AtomicI64::default(),
members: [(root, AgentPath::root())].into(),
active: AtomicBool::new(false),
notifications: Mutex::default(),
});
let board = LocalAgentMessageBoard::open(&sqlite, root.into(), host)
.await
.unwrap();
board
.create_channel(
root,
CreateChannelRequest {
channel_name: "Straße".into(),
subscription: SubscriptionChange::Unsubscribe,
},
)
.await
.unwrap();
let text = format!("Straße{}", "x".repeat(1000));
for index in 0..51 {
board
.post(
root,
PostRequest {
request_id: index.to_string(),
destination: PostDestination::Channel("Straße".into()),
text: text.clone(),
agents_to_notify: vec![],
},
)
.await
.unwrap();
}
let channels = board
.list_channels(
root,
ChannelQuery {
query: Some("STRASSE".into()),
direction: SortDirection::NewestFirst,
page: PageRequest::default(),
},
)
.await
.unwrap();
assert_eq!(channels.results.len(), 1);
let query = PostQuery {
channel_name: None,
query: Some("STRASSE".into()),
after_message_id: None,
author: None,
page: PageRequest {
cursor: None,
limit: NonZeroU32::MAX,
},
max_chars_per_post: NonZeroU32::MAX,
};
let page = board.search_posts(root, query.clone()).await.unwrap();
assert_eq!(page.results.len(), 50);
assert_eq!(
page.results
.iter()
.map(|post| post.text_preview.chars().count())
.sum::<usize>(),
20_000
);
assert!(page.results.iter().all(|post| post.truncated));
let last = board
.search_posts(
root,
PostQuery {
page: PageRequest {
cursor: page.next_cursor,
limit: NonZeroU32::MAX,
},
..query
},
)
.await
.unwrap();
assert_eq!(last.results.len(), 1);
assert_eq!(last.next_cursor, None);
}
#[tokio::test]
async fn queries_page_discussions_and_search_unicode() {
let dir = tempfile::tempdir().unwrap();
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into().unwrap());
let root = ThreadId::new();
let host = Arc::new(Host {
fail_notifications: AtomicBool::new(false),
clock: AtomicI64::default(),
members: [(root, AgentPath::root())].into(),
active: AtomicBool::new(true),
notifications: Mutex::default(),
});
let board: Arc<dyn AgentMessageBoard> = Arc::new(
LocalAgentMessageBoard::open(&sqlite, SessionId::from(root), host)
.await
.unwrap(),
);
let request = PostRequest {
request_id: "first".into(),
destination: PostDestination::NewChannel("work".into()),
text: "Éclair".into(),
agents_to_notify: vec![],
};
let first = board.post(root, request).await.unwrap();
let second = board
.post(
root,
PostRequest {
request_id: "second".into(),
destination: PostDestination::Channel("work".into()),
text: "second".into(),
agents_to_notify: vec![],
},
)
.await
.unwrap();
let one = NonZeroU32::new(1).unwrap();
let query = ThreadQuery {
channel_name: "work".into(),
sort: ThreadSort::Activity,
direction: SortDirection::OldestFirst,
page: PageRequest {
cursor: None,
limit: one,
},
max_chars_per_post: one,
};
let page = board.list_threads(root, query.clone()).await.unwrap();
assert_eq!(
page.results
.iter()
.map(|thread| thread.thread_id)
.collect::<Vec<_>>(),
vec![first.message_id]
);
let next = board
.list_threads(
root,
ThreadQuery {
page: PageRequest {
cursor: page.next_cursor,
limit: one,
},
..query.clone()
},
)
.await
.unwrap();
assert_eq!(
next.results
.iter()
.map(|thread| thread.thread_id)
.collect::<Vec<_>>(),
vec![second.message_id]
);
assert_eq!(next.next_cursor, None);
let reply = board
.post(
root,
PostRequest {
request_id: "reply".into(),
destination: PostDestination::Thread(first.message_id),
text: "ÉCLAIR🦀".into(),
agents_to_notify: vec![],
},
)
.await
.unwrap();
// A reply changes activity order without changing creation order.
let newest = ThreadQuery {
direction: SortDirection::NewestFirst,
..query
};
assert_eq!(
board
.list_threads(root, newest.clone())
.await
.unwrap()
.results,
vec![ThreadSummary {
thread_id: first.message_id,
root_post: PostPreview {
metadata: first.clone(),
text_preview: "É".into(),
n_chars: 6,
truncated: true,
},
reply_count: 1,
last_activity_at: reply.created_at,
latest_reply: Some(PostPreview {
metadata: reply.clone(),
text_preview: "É".into(),
n_chars: 7,
truncated: true,
}),
}]
);
let created = board
.list_threads(
root,
ThreadQuery {
sort: ThreadSort::Created,
..newest
},
)
.await
.unwrap();
assert_eq!(created.results[0].thread_id, second.message_id);
let search = board
.search_posts(
root,
PostQuery {
channel_name: Some("work".into()),
query: Some("éclair".into()),
after_message_id: Some(first.message_id),
author: Some(AgentPath::root()),
page: PageRequest::default(),
max_chars_per_post: one,
},
)
.await
.unwrap();
assert_eq!(
search,
Page {
results: vec![PostPreview {
metadata: reply.clone(),
text_preview: "É".into(),
n_chars: 7,
truncated: true
}],
next_cursor: None
}
);
let thread = board
.read_thread(
root,
ReadThreadRequest {
thread_id: first.message_id,
page: PageRequest::default(),
max_chars_per_post: one,
},
)
.await
.unwrap();
assert_eq!(
thread,
ThreadPage {
root_post: PostPreview {
metadata: first,
text_preview: "É".into(),
n_chars: 6,
truncated: true
},
replies: search
}
);
let serialized = serde_json::to_value(thread).unwrap();
assert_eq!(serialized["n_returned"], 1);
assert_eq!(serialized["has_more"], false);
let channels = board
.list_channels(
root,
ChannelQuery {
query: Some("WORK".into()),
direction: SortDirection::NewestFirst,
page: PageRequest::default(),
},
)
.await
.unwrap();
assert_eq!(channels.results[0].message_count, 3);
assert_eq!(channels.results[0].last_message_id, Some(reply.message_id));
assert!(
board
.read_thread(
root,
ReadThreadRequest {
thread_id: reply.message_id,
page: PageRequest::default(),
max_chars_per_post: one
}
)
.await
.is_err()
);
assert!(
board
.list_channels(
ThreadId::new(),
ChannelQuery {
query: None,
direction: SortDirection::NewestFirst,
page: PageRequest::default()
}
)
.await
.is_err()
);
}