Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(soup): frecency filter items + paginate (#188)

Sean Aye4f76272a976e
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index d405a0a36f..ab62e186dd 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3234,12 +3234,11 @@ name = "frecency"
version = "0.1.0"
dependencies = [
"anyhow",
- "aws-config",
"chrono",
"cool_asserts",
+ "filter_ast",
"futures",
"item_filters",
- "lambda_runtime",
"macro_db_migrator",
"macro_env",
"macro_env_var",
@@ -3250,6 +3249,7 @@ dependencies = [
"num-traits",
"ordered-float",
"rand 0.9.0",
+ "recursion",
"serde",
"serde_json",
"sqlx",
@@ -3257,6 +3257,7 @@ dependencies = [
"tokio",
"tower 0.5.2",
"tracing",
+ "uuid",
]
[[package]]
diff --git a/rust/cloud-storage/filter_ast/Cargo.toml b/rust/cloud-storage/filter_ast/Cargo.toml
index e57c3464a8..f31d5a65d6 100644
--- a/rust/cloud-storage/filter_ast/Cargo.toml
+++ b/rust/cloud-storage/filter_ast/Cargo.toml
@@ -4,7 +4,6 @@ name = "filter_ast"
publish = false
version = "0.1.0"
-
[dependencies]
recursion = { workspace = true }
serde = { workspace = true }
diff --git a/rust/cloud-storage/frecency/.sqlx/query-431678537eb817c74ba0e6ecc4b5ffe5e8b8a3b7efab1833dfcfe2ae5b0e79b4.json b/rust/cloud-storage/frecency/.sqlx/query-431678537eb817c74ba0e6ecc4b5ffe5e8b8a3b7efab1833dfcfe2ae5b0e79b4.json
deleted file mode 100644
index c477761075..0000000000
--- a/rust/cloud-storage/frecency/.sqlx/query-431678537eb817c74ba0e6ecc4b5ffe5e8b8a3b7efab1833dfcfe2ae5b0e79b4.json
+++ /dev/null
@@ -1,60 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT \n entity_id,\n entity_type,\n user_id,\n event_count,\n frecency_score,\n first_event,\n recent_events\n FROM frecency_aggregates\n WHERE user_id = $1 AND entity_type = $2 AND entity_id = $3\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "entity_id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "entity_type",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "user_id",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "event_count",
- "type_info": "Int4"
- },
- {
- "ordinal": 4,
- "name": "frecency_score",
- "type_info": "Float8"
- },
- {
- "ordinal": 5,
- "name": "first_event",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "recent_events",
- "type_info": "Jsonb"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- false,
- false
- ]
- },
- "hash": "431678537eb817c74ba0e6ecc4b5ffe5e8b8a3b7efab1833dfcfe2ae5b0e79b4"
-}
diff --git a/rust/cloud-storage/frecency/.sqlx/query-6f28cc8e7fbeec39222138e163c2eff0d63b1159c8f80e8c2821fbc3c820db9c.json b/rust/cloud-storage/frecency/.sqlx/query-e4e4c79727e7a83f2dfbb1d82a00a771eb3bd08aab63d2be4a1338fbde315f62.json
similarity index 79%
rename from rust/cloud-storage/frecency/.sqlx/query-6f28cc8e7fbeec39222138e163c2eff0d63b1159c8f80e8c2821fbc3c820db9c.json
rename to rust/cloud-storage/frecency/.sqlx/query-e4e4c79727e7a83f2dfbb1d82a00a771eb3bd08aab63d2be4a1338fbde315f62.json
index b4f3841609..f0ae8ed700 100644
--- a/rust/cloud-storage/frecency/.sqlx/query-6f28cc8e7fbeec39222138e163c2eff0d63b1159c8f80e8c2821fbc3c820db9c.json
+++ b/rust/cloud-storage/frecency/.sqlx/query-e4e4c79727e7a83f2dfbb1d82a00a771eb3bd08aab63d2be4a1338fbde315f62.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT *\n FROM frecency_aggregates\n WHERE user_id = $1\n ORDER BY frecency_score DESC\n LIMIT $2\n ",
+ "query": "\n SELECT *\n FROM frecency_aggregates\n WHERE user_id = $1 AND ($2::float8 IS NULL OR frecency_score < $2)\n ORDER BY frecency_score DESC\n LIMIT $3\n ",
"describe": {
"columns": [
{
@@ -47,6 +47,7 @@
"parameters": {
"Left": [
"Text",
+ "Float8",
"Int8"
]
},
@@ -61,5 +62,5 @@
false
]
},
- "hash": "6f28cc8e7fbeec39222138e163c2eff0d63b1159c8f80e8c2821fbc3c820db9c"
+ "hash": "e4e4c79727e7a83f2dfbb1d82a00a771eb3bd08aab63d2be4a1338fbde315f62"
}
diff --git a/rust/cloud-storage/frecency/Cargo.toml b/rust/cloud-storage/frecency/Cargo.toml
index 8af54ab645..dcda34e993 100644
--- a/rust/cloud-storage/frecency/Cargo.toml
+++ b/rust/cloud-storage/frecency/Cargo.toml
@@ -11,9 +11,9 @@ postgres = ["dep:serde_json", "dep:sqlx"]
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
+filter_ast = { path = "../filter_ast" }
futures = { workspace = true }
item_filters = { path = "../item_filters" }
-lambda_runtime = { workspace = true, optional = true, features = ["tracing"] }
macro_env = { path = "../macro_env" }
macro_env_var = { path = "../macro_env_var", optional = true }
macro_user_id = { path = "../macro_user_id" }
@@ -22,6 +22,7 @@ model-entity = { path = "../model-entity" }
models_pagination = { path = "../models_pagination" }
num-traits = { version = "0.2" }
ordered-float = "5"
+recursion = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, optional = true }
sqlx = { workspace = true, optional = true }
@@ -31,7 +32,8 @@ tower = { workspace = true, optional = true }
tracing = { workspace = true }
[dev-dependencies]
-aws-config = { workspace = true }
cool_asserts = "2"
+item_filters = { path = "../item_filters", features = ["mock"] }
macro_db_migrator = { path = "../macro_db_migrator" }
rand = { workspace = true }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/frecency/src/domain/ports.rs b/rust/cloud-storage/frecency/src/domain/ports.rs
index 770b0c8413..76da7299bd 100644
--- a/rust/cloud-storage/frecency/src/domain/ports.rs
+++ b/rust/cloud-storage/frecency/src/domain/ports.rs
@@ -57,8 +57,7 @@ pub trait AggregateFrecencyStorage: Send + Sync + 'static {
/// retrieve the top frecency score records for this user
fn get_top_entities(
&self,
- user_id: MacroUserIdStr<'_>,
- limit: u32,
+ req: FrecencyPageRequest<'_>,
) -> impl Future<Output = Result<Vec<AggregateFrecency>, Self::Err>> + Send;
/// write an [AggregateFrecency] back to storage
@@ -67,13 +66,6 @@ pub trait AggregateFrecencyStorage: Send + Sync + 'static {
frecency: AggregateFrecency,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
- /// retrieve the specific aggregate record for this entity + user pair
- fn get_aggregate_for_user_entity_pair(
- &self,
- user_id: MacroUserIdStr<'_>,
- entity: Entity<'_>,
- ) -> impl Future<Output = Result<Option<AggregateFrecency>, Self::Err>> + Send;
-
/// retrieve the specific aggregate record for the input entities + user pair
fn get_aggregate_for_user_entities<T>(
&self,
diff --git a/rust/cloud-storage/frecency/src/domain/services.rs b/rust/cloud-storage/frecency/src/domain/services.rs
index b46c4abfd2..1c9d0bd596 100644
--- a/rust/cloud-storage/frecency/src/domain/services.rs
+++ b/rust/cloud-storage/frecency/src/domain/services.rs
@@ -255,7 +255,7 @@ where
) -> Result<FrecencyPageResponse, FrecencyQueryErr> {
let res = self
.storage
- .get_top_entities(query.user_id, query.limit)
+ .get_top_entities(query)
.await
.map_err(anyhow::Error::from)?;
Ok(FrecencyPageResponse::new(res))
diff --git a/rust/cloud-storage/frecency/src/outbound/mock.rs b/rust/cloud-storage/frecency/src/outbound/mock.rs
index 6aa2798f72..223e87b4f0 100644
--- a/rust/cloud-storage/frecency/src/outbound/mock.rs
+++ b/rust/cloud-storage/frecency/src/outbound/mock.rs
@@ -1,5 +1,5 @@
//! This module provides an [mockall::mock] concrete struct [MockFrecencyStorage] which can be used for testing
-use crate::domain::ports::AggregateFrecencyStorage;
+use crate::domain::{models::FrecencyPageRequest, ports::AggregateFrecencyStorage};
use macro_user_id::user_id::MacroUserIdStr;
use mockall::mock;
use model_entity::Entity;
@@ -17,14 +17,11 @@ mock! {
impl AggregateFrecencyStorage for FrecencyStorage {
type Err = Infallible;
- fn get_top_entities<'b>(&self, user_id: MacroUserIdStr<'b>, limit: u32) -> impl Future<Output = Result<Vec<crate::domain::models::AggregateFrecency>, Infallible>> + Send;
+ fn get_top_entities<'b>(&self, req: FrecencyPageRequest<'b>) -> impl Future<Output = Result<Vec<crate::domain::models::AggregateFrecency>, Infallible>> + Send;
fn set_aggregate(&self, frecency: crate::domain::models::AggregateFrecency) -> impl Future<Output = Result<(), Infallible>> + Send;
- fn get_aggregate_for_user_entity_pair<'b, 'c>(&self, user_id: MacroUserIdStr<'b>, entity: Entity<'c>) -> impl Future<Output = Result<Option<crate::domain::models::AggregateFrecency>, Infallible>> + Send;
-
-
#[mockall::concretize]
fn get_aggregate_for_user_entities<T: Iterator<Item = Entity<'static>>>(
&self,
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres.rs b/rust/cloud-storage/frecency/src/outbound/postgres.rs
index bc4ea24b4e..e8e9f7e0dc 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres.rs
@@ -2,11 +2,12 @@
use crate::domain::{
models::{
AggregateFrecency, AggregateId, EventRecord, EventRecordWithId, FrecencyData,
- TimestampWeight,
+ FrecencyPageRequest, TimestampWeight,
},
ports::{AggregateFrecencyStorage, EventRecordStorage, UnprocessedEventsRepo},
};
use chrono::{DateTime, Utc};
+use item_filters::ast::EntityFilterAst;
use macro_user_id::{
cowlike::CowLike,
user_id::{MacroUserIdStr, ParseErr},
@@ -16,20 +17,89 @@ use sqlx::{PgPool, Postgres, QueryBuilder, Row, Transaction, prelude::FromRow};
use std::{borrow::Cow, collections::VecDeque, str::FromStr};
use thiserror::Error;
+mod dynamic;
+
#[cfg(test)]
mod tests;
+#[cfg(test)]
+mod dynamic_tests;
+
/// Concrete implementation of storage ports against a postgres instance
#[derive(Debug, Clone)]
pub struct FrecencyPgStorage {
pool: PgPool,
}
+/// the types of errors that can occur on [FrecencyPgStorage]
+#[derive(Debug, Error)]
+pub enum FrecencyStorageErr {
+ /// there was a sqlx error
+ #[error(transparent)]
+ Db(#[from] sqlx::Error),
+ /// the database contained invalid user id data
+ #[error(transparent)]
+ UserIdErr(#[from] ParseErr),
+ /// encounted an unknown entity type
+ #[error(transparent)]
+ UnknownEntity(#[from] model_entity::ParseError),
+ /// failed to deserialize a type from json
+ #[error(transparent)]
+ Serde(#[from] serde_json::Error),
+}
+
impl FrecencyPgStorage {
/// create a new instance of Self
pub fn new(pool: PgPool) -> Self {
FrecencyPgStorage { pool }
}
+
+ async fn static_get_top_entities(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ from_score: Option<f64>,
+ limit: u32,
+ ) -> Result<Vec<AggregateFrecency>, FrecencyStorageErr> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT *
+ FROM frecency_aggregates
+ WHERE user_id = $1 AND ($2::float8 IS NULL OR frecency_score < $2)
+ ORDER BY frecency_score DESC
+ LIMIT $3
+ "#,
+ user_id.as_ref(),
+ from_score,
+ limit as i64
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ rows.into_iter()
+ .map(|row| {
+ let aggregate_row = AggregateRow {
+ entity_id: row.entity_id,
+ entity_type: row.entity_type.parse()?,
+ user_id: row.user_id,
+ event_count: row.event_count as usize,
+ frecency_score: row.frecency_score,
+ first_event: row.first_event,
+ recent_events: serde_json::from_value(row.recent_events)?,
+ };
+ Ok(aggregate_row.into_aggregate_frecency()?)
+ })
+ .collect()
+ }
+
+ async fn dynamic_get_top_entities(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ from_score: Option<f64>,
+ limit: u32,
+ filter: EntityFilterAst,
+ ) -> Result<Vec<AggregateFrecency>, FrecencyStorageErr> {
+ dynamic::dynamic_get_top_entities(&self.pool, user_id, from_score, limit, filter).await
+ }
}
struct EventRow<'a, T> {
@@ -175,43 +245,28 @@ impl AggregateRow {
}
impl AggregateFrecencyStorage for FrecencyPgStorage {
- type Err = anyhow::Error;
+ type Err = FrecencyStorageErr;
async fn get_top_entities(
&self,
- user_id: MacroUserIdStr<'_>,
- limit: u32,
- ) -> Result<Vec<crate::domain::models::AggregateFrecency>, Self::Err> {
- let rows = sqlx::query!(
- r#"
- SELECT *
- FROM frecency_aggregates
- WHERE user_id = $1
- ORDER BY frecency_score DESC
- LIMIT $2
- "#,
- user_id.as_ref(),
- limit as i64
- )
- .fetch_all(&self.pool)
- .await?;
-
- let out: Result<Vec<_>, _> = rows
- .into_iter()
- .map(|row| {
- let aggregate_row = AggregateRow {
- entity_id: row.entity_id,
- entity_type: row.entity_type.parse().unwrap(),
- user_id: row.user_id,
- event_count: row.event_count as usize,
- frecency_score: row.frecency_score,
- first_event: row.first_event,
- recent_events: serde_json::from_value(row.recent_events).unwrap(),
- };
- aggregate_row.into_aggregate_frecency()
- })
- .collect();
- Ok(out?)
+ req: FrecencyPageRequest<'_>,
+ ) -> Result<Vec<AggregateFrecency>, Self::Err> {
+ let FrecencyPageRequest {
+ user_id,
+ from_score,
+ limit,
+ filters,
+ } = req;
+ match filters {
+ None => {
+ self.static_get_top_entities(user_id, from_score, limit)
+ .await
+ }
+ Some(filter) => {
+ self.dynamic_get_top_entities(user_id, from_score, limit, filter)
+ .await
+ }
+ }
}
async fn set_aggregate(
@@ -255,50 +310,6 @@ impl AggregateFrecencyStorage for FrecencyPgStorage {
Ok(())
}
- async fn get_aggregate_for_user_entity_pair(
- &self,
- user_id: MacroUserIdStr<'_>,
- entity: Entity<'_>,
- ) -> Result<Option<crate::domain::models::AggregateFrecency>, Self::Err> {
- let entity_type = entity.entity_type.to_string();
- let entity_id = entity.entity_id.into_owned();
-
- let row = sqlx::query!(
- r#"
- SELECT
- entity_id,
- entity_type,
- user_id,
- event_count,
- frecency_score,
- first_event,
- recent_events
- FROM frecency_aggregates
- WHERE user_id = $1 AND entity_type = $2 AND entity_id = $3
- "#,
- user_id.as_ref(),
- entity_type,
- entity_id
- )
- .fetch_optional(&self.pool)
- .await?;
-
- Ok(row
- .map(|row| {
- let aggregate_row = AggregateRow {
- entity_id: row.entity_id,
- entity_type: row.entity_type.parse().unwrap(),
- user_id: row.user_id.to_string(),
- event_count: row.event_count as usize,
- frecency_score: row.frecency_score,
- first_event: row.first_event,
- recent_events: serde_json::from_value(row.recent_events).unwrap(),
- };
- aggregate_row.into_aggregate_frecency()
- })
- .transpose()?)
- }
-
async fn get_aggregate_for_user_entities<T>(
&self,
user_id: MacroUserIdStr<'static>,
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
new file mode 100644
index 0000000000..c846f1012d
--- /dev/null
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
@@ -0,0 +1,227 @@
+//! This module provides dynamic query building for frecency queries with filters
+
+use crate::domain::models::{AggregateFrecency, AggregateId, FrecencyData, TimestampWeight};
+use filter_ast::Expr;
+use item_filters::ast::{
+ EntityFilterAst, chat::ChatLiteral, document::DocumentLiteral, project::ProjectLiteral,
+};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use model_entity::EntityType;
+use recursion::CollapsibleExt;
+use sqlx::{PgPool, Postgres, QueryBuilder, postgres::PgRow, prelude::FromRow};
+use std::collections::VecDeque;
+
+use super::FrecencyStorageErr;
+
+static DOCUMENT_CLAUSE: &str = r#"
+ SELECT
+ entity_id,
+ 'document' as entity_type,
+ user_id,
+ event_count,
+ frecency_score,
+ first_event,
+ recent_events
+ FROM frecency_aggregates
+ WHERE user_id = $1 AND entity_type = 'document'
+"#;
+
+static CHAT_CLAUSE: &str = r#"
+ SELECT
+ entity_id,
+ 'chat' as entity_type,
+ user_id,
+ event_count,
+ frecency_score,
+ first_event,
+ recent_events
+ FROM frecency_aggregates
+ WHERE user_id = $1 AND entity_type = 'chat'
+"#;
+
+static PROJECT_CLAUSE: &str = r#"
+ SELECT
+ entity_id,
+ 'project' as entity_type,
+ user_id,
+ event_count,
+ frecency_score,
+ first_event,
+ recent_events
+ FROM frecency_aggregates
+ WHERE user_id = $1 AND entity_type = 'project'
+"#;
+
+static SUFFIX: &str = r#"
+ SELECT * FROM Combined
+ WHERE ($2::float8 IS NULL OR frecency_score < $2)
+ ORDER BY frecency_score DESC
+ LIMIT $3
+"#;
+
+fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>) -> String {
+ let Some(expr) = ast else {
+ return String::new();
+ };
+ let formatting = expr.collapse_frames(|frame| match frame {
+ filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
+ filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
+ filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
+ filter_ast::ExprFrame::Literal(DocumentLiteral::FileType(f)) => {
+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "fileType" = '{f}' AND "deletedAt" IS NULL)"#)
+ }
+ filter_ast::ExprFrame::Literal(DocumentLiteral::Id(i)) => format!("entity_id = '{i}'"),
+ filter_ast::ExprFrame::Literal(DocumentLiteral::ProjectId(p)) => {
+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "projectId" = '{p}' AND "deletedAt" IS NULL)"#)
+ }
+ filter_ast::ExprFrame::Literal(DocumentLiteral::Owner(o)) => {
+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE owner = '{o}' AND "deletedAt" IS NULL)"#)
+ }
+ });
+ if formatting.is_empty() {
+ String::new()
+ } else {
+ format!(" AND {}", formatting)
+ }
+}
+
+fn build_chat_filter(ast: Option<&Expr<ChatLiteral>>) -> String {
+ let Some(expr) = ast else {
+ return String::new();
+ };
+ let formatting = expr.collapse_frames(|frame| match frame {
+ filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
+ filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
+ filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
+ filter_ast::ExprFrame::Literal(ChatLiteral::ProjectId(p)) => {
+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "projectId" = '{p}' AND "deletedAt" IS NULL)"#)
+ }
+ filter_ast::ExprFrame::Literal(ChatLiteral::Role(_r)) => {
+ // Chat role filtering doesn't apply to frecency aggregates
+ String::new()
+ }
+ filter_ast::ExprFrame::Literal(ChatLiteral::ChatId(i)) => format!("entity_id = '{i}'"),
+ filter_ast::ExprFrame::Literal(ChatLiteral::Owner(o)) => {
+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "userId" = '{o}' AND "deletedAt" IS NULL)"#)
+ }
+ });
+ if formatting.is_empty() {
+ String::new()
+ } else {
+ format!(" AND {}", formatting)
+ }
+}
+
+fn build_project_filter(ast: Option<&Expr<ProjectLiteral>>) -> String {
+ let Some(expr) = ast else {
+ return String::new();
+ };
+ let formatting = expr.collapse_frames(|frame| match frame {
+ filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
+ filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
+ filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
+ filter_ast::ExprFrame::Literal(ProjectLiteral::ProjectId(p)) => {
+ format!("entity_id = '{p}'")
+ }
+ filter_ast::ExprFrame::Literal(ProjectLiteral::Owner(o)) => {
+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "userId" = '{o}' AND "deletedAt" IS NULL)"#)
+ }
+ });
+ if formatting.is_empty() {
+ String::new()
+ } else {
+ format!(" AND {}", formatting)
+ }
+}
+
+fn build_query(filter_ast: &EntityFilterAst) -> QueryBuilder<'_, Postgres> {
+ let mut builder = sqlx::QueryBuilder::new("WITH Combined AS (");
+
+ // Document clause
+ builder.push(DOCUMENT_CLAUSE);
+ builder.push(build_document_filter(
+ filter_ast.inner.document_filter.as_ref(),
+ ));
+
+ builder.push(" UNION ALL ");
+
+ // Chat clause
+ builder.push(CHAT_CLAUSE);
+ builder.push(build_chat_filter(filter_ast.inner.chat_filter.as_ref()));
+
+ builder.push(" UNION ALL ");
+
+ // Project clause
+ builder.push(PROJECT_CLAUSE);
+ builder.push(build_project_filter(
+ filter_ast.inner.project_filter.as_ref(),
+ ));
+
+ builder.push(") ");
+ builder.push(SUFFIX);
+
+ builder
+}
+
+#[derive(FromRow)]
+struct AggregateRow {
+ entity_id: String,
+ #[sqlx(try_from = "String")]
+ entity_type: EntityType,
+ user_id: String,
+ #[sqlx(try_from = "i32")]
+ event_count: usize,
+ frecency_score: f64,
+ first_event: chrono::DateTime<chrono::Utc>,
+ recent_events: sqlx::types::Json<VecDeque<TimestampWeight>>,
+}
+
+impl AggregateRow {
+ fn into_aggregate_frecency(self) -> Result<AggregateFrecency, sqlx::Error> {
+ let AggregateRow {
+ entity_id,
+ entity_type,
+ user_id,
+ event_count,
+ frecency_score,
+ first_event,
+ recent_events,
+ } = self;
+
+ let user_id = MacroUserIdStr::parse_from_str(&user_id)
+ .map(|id| id.into_owned())
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
+
+ Ok(AggregateFrecency {
+ id: AggregateId {
+ entity: entity_type.with_entity_string(entity_id.to_string()),
+ user_id,
+ },
+ data: FrecencyData {
+ event_count,
+ frecency_score,
+ first_event,
+ recent_events: recent_events.0,
+ },
+ })
+ }
+}
+
+pub async fn dynamic_get_top_entities(
+ db: &PgPool,
+ user_id: MacroUserIdStr<'_>,
+ from_score: Option<f64>,
+ limit: u32,
+ filter: EntityFilterAst,
+) -> Result<Vec<AggregateFrecency>, FrecencyStorageErr> {
+ let rows = build_query(&filter)
+ .build()
+ .bind(user_id.as_ref())
+ .bind(from_score)
+ .bind(limit as i64)
+ .try_map(|row: PgRow| AggregateRow::from_row(&row)?.into_aggregate_frecency())
+ .fetch_all(db)
+ .await?;
+
+ Ok(rows)
+}
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
new file mode 100644
index 0000000000..4d1ce6a387
--- /dev/null
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
@@ -0,0 +1,438 @@
+//! Tests for dynamic frecency filtering
+
+use super::*;
+use crate::domain::models::{AggregateId, FrecencyData};
+use chrono::Utc;
+use item_filters::{ChatFilters, DocumentFilters, EntityFilters, ProjectFilters};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use model_entity::EntityType;
+use std::collections::VecDeque;
+use uuid::Uuid;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_dynamic_filter_by_document_ids(pool: PgPool) {
+ let storage = FrecencyPgStorage::new(pool.clone());
+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Create test UUIDs
+ let doc_id_1 = Uuid::new_v4();
+ let doc_id_2 = Uuid::new_v4();
+ let chat_id_1 = Uuid::new_v4();
+
+ // Create aggregates
+ for (id, entity_type, score) in [
+ (doc_id_1.to_string(), EntityType::Document, 100.0),
+ (doc_id_2.to_string(), EntityType::Document, 80.0),
+ (chat_id_1.to_string(), EntityType::Chat, 90.0),
+ ] {
+ storage
+ .set_aggregate(AggregateFrecency {
+ id: AggregateId {
+ entity: entity_type.with_entity_string(id.clone()),
+ user_id: test_user_id.clone(),
+ },
+ data: FrecencyData {
+ event_count: 1,
+ frecency_score: score,
+ first_event: Utc::now(),
+ recent_events: VecDeque::new(),
+ },
+ })
+ .await
+ .unwrap();
+ }
+
+ // Filter for specific document ID
+ let filter = item_filters::ast::EntityFilterAst::new_from_filters(EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec![doc_id_1.to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ })
+ .unwrap()
+ .unwrap();
+
+ let results = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 10,
+ filters: Some(filter),
+ })
+ .await
+ .unwrap();
+
+ // Should return filtered document (doc_id_1) + all chats (chat_id_1)
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].id.entity.entity_id, doc_id_1.to_string());
+ assert_eq!(results[0].data.frecency_score, 100.0);
+ assert_eq!(results[1].id.entity.entity_id, chat_id_1.to_string());
+ assert_eq!(results[1].data.frecency_score, 90.0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_dynamic_filter_by_chat_ids(pool: PgPool) {
+ let storage = FrecencyPgStorage::new(pool.clone());
+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let chat_id_1 = Uuid::new_v4();
+ let chat_id_2 = Uuid::new_v4();
+ let doc_id_1 = Uuid::new_v4();
+
+ for (id, entity_type, score) in [
+ (chat_id_1.to_string(), EntityType::Chat, 100.0),
+ (chat_id_2.to_string(), EntityType::Chat, 80.0),
+ (doc_id_1.to_string(), EntityType::Document, 90.0),
+ ] {
+ storage
+ .set_aggregate(AggregateFrecency {
+ id: AggregateId {
+ entity: entity_type.with_entity_string(id.clone()),
+ user_id: test_user_id.clone(),
+ },
+ data: FrecencyData {
+ event_count: 1,
+ frecency_score: score,
+ first_event: Utc::now(),
+ recent_events: VecDeque::new(),
+ },
+ })
+ .await
+ .unwrap();
+ }
+
+ let filter = item_filters::ast::EntityFilterAst::new_from_filters(EntityFilters {
+ chat_filters: ChatFilters {
+ chat_ids: vec![chat_id_1.to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ })
+ .unwrap()
+ .unwrap();
+
+ let results = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 10,
+ filters: Some(filter),
+ })
+ .await
+ .unwrap();
+
+ // Should return filtered chat (chat_id_1) + all documents (doc_id_1)
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].id.entity.entity_id, chat_id_1.to_string());
+ assert_eq!(results[0].data.frecency_score, 100.0);
+ assert_eq!(results[1].id.entity.entity_id, doc_id_1.to_string());
+ assert_eq!(results[1].data.frecency_score, 90.0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_dynamic_filter_by_project_ids(pool: PgPool) {
+ let storage = FrecencyPgStorage::new(pool.clone());
+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let project_id_1 = Uuid::new_v4();
+ let project_id_2 = Uuid::new_v4();
+ let doc_id_1 = Uuid::new_v4();
+
+ for (id, entity_type, score) in [
+ (project_id_1.to_string(), EntityType::Project, 100.0),
+ (project_id_2.to_string(), EntityType::Project, 80.0),
+ (doc_id_1.to_string(), EntityType::Document, 90.0),
+ ] {
+ storage
+ .set_aggregate(AggregateFrecency {
+ id: AggregateId {
+ entity: entity_type.with_entity_string(id.clone()),
+ user_id: test_user_id.clone(),
+ },
+ data: FrecencyData {
+ event_count: 1,
+ frecency_score: score,
+ first_event: Utc::now(),
+ recent_events: VecDeque::new(),
+ },
+ })
+ .await
+ .unwrap();
+ }
+
+ let filter = item_filters::ast::EntityFilterAst::new_from_filters(EntityFilters {
+ project_filters: ProjectFilters {
+ project_ids: vec![project_id_1.to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ })
+ .unwrap()
+ .unwrap();
+
+ let results = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 10,
+ filters: Some(filter),
+ })
+ .await
+ .unwrap();
+
+ // Should return filtered project (project_id_1) + all documents (doc_id_1)
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].id.entity.entity_id, project_id_1.to_string());
+ assert_eq!(results[0].data.frecency_score, 100.0);
+ assert_eq!(results[1].id.entity.entity_id, doc_id_1.to_string());
+ assert_eq!(results[1].data.frecency_score, 90.0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_dynamic_filter_multiple_document_ids(pool: PgPool) {
+ let storage = FrecencyPgStorage::new(pool.clone());
+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let doc_id_1 = Uuid::new_v4();
+ let doc_id_2 = Uuid::new_v4();
+ let doc_id_3 = Uuid::new_v4();
+
+ for (id, entity_type, score) in [
+ (doc_id_1.to_string(), EntityType::Document, 100.0),
+ (doc_id_2.to_string(), EntityType::Document, 90.0),
+ (doc_id_3.to_string(), EntityType::Document, 80.0),
+ ] {
+ storage
+ .set_aggregate(AggregateFrecency {
+ id: AggregateId {
+ entity: entity_type.with_entity_string(id.clone()),
+ user_id: test_user_id.clone(),
+ },
+ data: FrecencyData {
+ event_count: 1,
+ frecency_score: score,
+ first_event: Utc::now(),
+ recent_events: VecDeque::new(),
+ },
+ })
+ .await
+ .unwrap();
+ }
+
+ // Filter for two of the three documents (OR filter)
+ let filter = item_filters::ast::EntityFilterAst::new_from_filters(EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec![doc_id_1.to_string(), doc_id_2.to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ })
+ .unwrap()
+ .unwrap();
+
+ let results = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 10,
+ filters: Some(filter),
+ })
+ .await
+ .unwrap();
+
+ // Should return 2 filtered documents (no chats/projects exist in this test)
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].id.entity.entity_id, doc_id_1.to_string());
+ assert_eq!(results[0].data.frecency_score, 100.0);
+ assert_eq!(results[1].id.entity.entity_id, doc_id_2.to_string());
+ assert_eq!(results[1].data.frecency_score, 90.0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_dynamic_filter_mixed_entity_types(pool: PgPool) {
+ let storage = FrecencyPgStorage::new(pool.clone());
+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let doc_id_1 = Uuid::new_v4();
+ let chat_id_1 = Uuid::new_v4();
+ let project_id_1 = Uuid::new_v4();
+ let doc_id_2 = Uuid::new_v4();
+
+ for (id, entity_type, score) in [
+ (doc_id_1.to_string(), EntityType::Document, 100.0),
+ (chat_id_1.to_string(), EntityType::Chat, 90.0),
+ (project_id_1.to_string(), EntityType::Project, 80.0),
+ (doc_id_2.to_string(), EntityType::Document, 70.0),
+ ] {
+ storage
+ .set_aggregate(AggregateFrecency {
+ id: AggregateId {
+ entity: entity_type.with_entity_string(id.clone()),
+ user_id: test_user_id.clone(),
+ },
+ data: FrecencyData {
+ event_count: 1,
+ frecency_score: score,
+ first_event: Utc::now(),
+ recent_events: VecDeque::new(),
+ },
+ })
+ .await
+ .unwrap();
+ }
+
+ // Filter for one document and one chat
+ let filter = item_filters::ast::EntityFilterAst::new_from_filters(EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec![doc_id_1.to_string()],
+ ..Default::default()
+ },
+ chat_filters: ChatFilters {
+ chat_ids: vec![chat_id_1.to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ })
+ .unwrap()
+ .unwrap();
+
+ let results = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 10,
+ filters: Some(filter),
+ })
+ .await
+ .unwrap();
+
+ // Should return filtered doc + filtered chat + all projects
+ assert_eq!(results.len(), 3);
+ assert_eq!(results[0].id.entity.entity_id, doc_id_1.to_string());
+ assert_eq!(results[0].data.frecency_score, 100.0);
+ assert_eq!(results[1].id.entity.entity_id, chat_id_1.to_string());
+ assert_eq!(results[1].data.frecency_score, 90.0);
+ assert_eq!(results[2].id.entity.entity_id, project_id_1.to_string());
+ assert_eq!(results[2].data.frecency_score, 80.0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_dynamic_filter_with_from_score_pagination(pool: PgPool) {
+ let storage = FrecencyPgStorage::new(pool.clone());
+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let doc_id_1 = Uuid::new_v4();
+ let doc_id_2 = Uuid::new_v4();
+ let doc_id_3 = Uuid::new_v4();
+ let chat_id_1 = Uuid::new_v4();
+
+ for (id, entity_type, score) in [
+ (doc_id_1.to_string(), EntityType::Document, 100.0),
+ (doc_id_2.to_string(), EntityType::Document, 80.0),
+ (doc_id_3.to_string(), EntityType::Document, 60.0),
+ (chat_id_1.to_string(), EntityType::Chat, 90.0),
+ ] {
+ storage
+ .set_aggregate(AggregateFrecency {
+ id: AggregateId {
+ entity: entity_type.with_entity_string(id.clone()),
+ user_id: test_user_id.clone(),
+ },
+ data: FrecencyData {
+ event_count: 1,
+ frecency_score: score,
+ first_event: Utc::now(),
+ recent_events: VecDeque::new(),
+ },
+ })
+ .await
+ .unwrap();
+ }
+
+ // Filter for all three documents
+ let filter = item_filters::ast::EntityFilterAst::new_from_filters(EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec![
+ doc_id_1.to_string(),
+ doc_id_2.to_string(),
+ doc_id_3.to_string(),
+ ],
+ ..Default::default()
+ },
+ ..Default::default()
+ })
+ .unwrap()
+ .unwrap();
+
+ // Use from_score to paginate (filter out items with score >= 85.0)
+ let results = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: Some(85.0),
+ limit: 10,
+ filters: Some(filter),
+ })
+ .await
+ .unwrap();
+
+ // Should return filtered docs with score < 85 + all chats with score < 85
+ // doc_id_1 (100) filtered out by from_score
+ // doc_id_2 (80) included
+ // doc_id_3 (60) included
+ // chat_id_1 (90) filtered out by from_score
+ assert_eq!(results.len(), 2);
+ assert_eq!(results[0].id.entity.entity_id, doc_id_2.to_string());
+ assert_eq!(results[0].data.frecency_score, 80.0);
+ assert_eq!(results[1].id.entity.entity_id, doc_id_3.to_string());
+ assert_eq!(results[1].data.frecency_score, 60.0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_dynamic_filter_no_matches(pool: PgPool) {
+ let storage = FrecencyPgStorage::new(pool.clone());
+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ let doc_id_1 = Uuid::new_v4();
+ let non_existent_id = Uuid::new_v4();
+
+ storage
+ .set_aggregate(AggregateFrecency {
+ id: AggregateId {
+ entity: EntityType::Document.with_entity_string(doc_id_1.to_string()),
+ user_id: test_user_id.clone(),
+ },
+ data: FrecencyData {
+ event_count: 1,
+ frecency_score: 100.0,
+ first_event: Utc::now(),
+ recent_events: VecDeque::new(),
+ },
+ })
+ .await
+ .unwrap();
+
+ // Filter for non-existent document
+ let filter = item_filters::ast::EntityFilterAst::new_from_filters(EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec![non_existent_id.to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ })
+ .unwrap()
+ .unwrap();
+
+ let results = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 10,
+ filters: Some(filter),
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(results.len(), 0);
+}
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs
index e4f59d9516..192d4982e5 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs
@@ -47,7 +47,7 @@ async fn test_set_event(pool: PgPool) {
assert_eq!(row.event_type, "open");
assert_eq!(row.entity_id, "doc123");
assert_eq!(row.connection_id, "conn456");
- assert_eq!(row.was_processed, false);
+ assert!(!row.was_processed);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
@@ -81,15 +81,16 @@ async fn test_set_and_get_aggregate(pool: PgPool) {
// Retrieve the aggregate
let retrieved = storage
- .get_aggregate_for_user_entity_pair(
- test_user_id.copied(),
- EntityType::Document.with_entity_str("doc456"),
- )
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 1,
+ filters: None,
+ })
.await
.unwrap();
- assert!(retrieved.is_some());
- let retrieved = retrieved.unwrap();
+ let retrieved = retrieved.into_iter().next().unwrap();
assert_eq!(retrieved.id.user_id.as_ref(), test_user_id.as_ref());
assert_eq!(retrieved.id.entity.entity_id, "doc456");
assert_eq!(retrieved.id.entity.entity_type, EntityType::Document);
@@ -143,12 +144,16 @@ async fn test_update_aggregate(pool: PgPool) {
// Verify the update
let retrieved = storage
- .get_aggregate_for_user_entity_pair(
- test_user_id,
- EntityType::Chat.with_entity_str("chat789"),
- )
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 1,
+ filters: None,
+ })
.await
.unwrap()
+ .into_iter()
+ .next()
.unwrap();
assert_eq!(retrieved.data.event_count, 10);
@@ -188,7 +193,12 @@ async fn test_get_top_entities(pool: PgPool) {
// Get top 3 entities
let top_entities = storage
- .get_top_entities(test_user_id.clone(), 3)
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 3,
+ filters: None,
+ })
.await
.unwrap();
@@ -250,24 +260,6 @@ async fn test_get_aggregate_for_user_entities(pool: PgPool) {
assert_eq!(results[1].data.frecency_score, 80.0);
}
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn test_get_aggregate_for_nonexistent_entity(pool: PgPool) {
- let storage = FrecencyPgStorage::new(pool.clone());
- let test_user_id =
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
-
- // Try to get a non-existent aggregate
- let result = storage
- .get_aggregate_for_user_entity_pair(
- test_user_id.copied(),
- EntityType::Document.with_entity_str("nonexistent"),
- )
- .await
- .unwrap();
-
- assert!(result.is_none());
-}
-
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_top_entities_empty(pool: PgPool) {
let storage = FrecencyPgStorage::new(pool.clone());
@@ -276,7 +268,12 @@ async fn test_get_top_entities_empty(pool: PgPool) {
// Get top entities for user with no data
let top_entities = storage
- .get_top_entities(test_user_id.copied(), 10)
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 10,
+ filters: None,
+ })
.await
.unwrap();
@@ -299,6 +296,128 @@ async fn test_get_aggregate_for_empty_entities_list(pool: PgPool) {
// Tests for FrecencyPgProcessor
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_get_top_entities_with_from_score(pool: PgPool) {
+ let storage = FrecencyPgStorage::new(pool.clone());
+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Create multiple aggregates with different scores
+ let entities = vec![
+ ("doc1", EntityType::Document, 100.0),
+ ("doc2", EntityType::Document, 80.0),
+ ("chat1", EntityType::Chat, 60.0),
+ ("project1", EntityType::Project, 40.0),
+ ("doc3", EntityType::Document, 20.0),
+ ];
+
+ for (id, entity_type, score) in entities {
+ let aggregate = AggregateFrecency {
+ id: AggregateId {
+ entity: entity_type.with_entity_string(id.to_string()),
+ user_id: test_user_id.clone(),
+ },
+ data: FrecencyData {
+ event_count: 1,
+ frecency_score: score,
+ first_event: Utc::now(),
+ recent_events: VecDeque::new(),
+ },
+ };
+ storage.set_aggregate(aggregate).await.unwrap();
+ }
+
+ // Test 1: Get all top entities without from_score
+ let all_entities = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 10,
+ filters: None,
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(all_entities.len(), 5);
+ assert_eq!(all_entities[0].id.entity.entity_id, "doc1");
+ assert_eq!(all_entities[0].data.frecency_score, 100.0);
+
+ // Test 2: Get entities with score < 80.0 (should get 60, 40, 20)
+ let filtered_entities = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: Some(80.0),
+ limit: 10,
+ filters: None,
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(filtered_entities.len(), 3);
+ assert_eq!(filtered_entities[0].id.entity.entity_id, "chat1");
+ assert_eq!(filtered_entities[0].data.frecency_score, 60.0);
+ assert_eq!(filtered_entities[1].id.entity.entity_id, "project1");
+ assert_eq!(filtered_entities[1].data.frecency_score, 40.0);
+ assert_eq!(filtered_entities[2].id.entity.entity_id, "doc3");
+ assert_eq!(filtered_entities[2].data.frecency_score, 20.0);
+
+ // Test 3: Pagination - get top 2, then next 2
+ let page1 = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: None,
+ limit: 2,
+ filters: None,
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(page1.len(), 2);
+ assert_eq!(page1[0].data.frecency_score, 100.0);
+ assert_eq!(page1[1].data.frecency_score, 80.0);
+
+ // Use the last score from page1 to get the next page
+ let last_score = page1.last().unwrap().data.frecency_score;
+ let page2 = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: Some(last_score),
+ limit: 2,
+ filters: None,
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(page2.len(), 2);
+ assert_eq!(page2[0].data.frecency_score, 60.0);
+ assert_eq!(page2[1].data.frecency_score, 40.0);
+
+ // Test 4: from_score lower than all scores (should return empty)
+ let no_entities = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: Some(10.0),
+ limit: 10,
+ filters: None,
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(no_entities.len(), 0);
+
+ // Test 5: from_score higher than all scores (should return all)
+ let all_with_high_score = storage
+ .get_top_entities(FrecencyPageRequest {
+ user_id: test_user_id.copied(),
+ from_score: Some(150.0),
+ limit: 10,
+ filters: None,
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(all_with_high_score.len(), 5);
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_processor_get_unprocessed_events(pool: PgPool) {
let processor = FrecencyPgProcessor::new(pool.clone());
diff --git a/rust/cloud-storage/macro_db_client/fixtures/no_frecency_items.sql b/rust/cloud-storage/macro_db_client/fixtures/no_frecency_items.sql
index d3484c8b38..b44c1f65f7 100644
--- a/rust/cloud-storage/macro_db_client/fixtures/no_frecency_items.sql
+++ b/rust/cloud-storage/macro_db_client/fixtures/no_frecency_items.sql
@@ -13,66 +13,66 @@ VALUES ('macro|[email protected]', '[email protected]', 'stripe_id_1', '1');
-- Project Hierarchy
INSERT INTO public."Project" ("id", "name", "userId", "createdAt", "updatedAt")
-VALUES ('project-A', 'Project A', 'macro|[email protected]', '2024-01-01 09:00:00', '2024-01-01 09:00:00');
+VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Project A', 'macro|[email protected]', '2024-01-01 09:00:00', '2024-01-01 09:00:00');
-- Give user access to the project
INSERT INTO public."UserItemAccess" ("id", "user_id", "item_id", "item_type", "access_level")
-VALUES (gen_random_uuid(), 'macro|[email protected]', 'project-A', 'project', 'owner');
+VALUES (gen_random_uuid(), 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'project', 'owner');
-- Create documents (3 with frecency, 2 without)
-- Documents WITH frecency (should be filtered out)
INSERT INTO public."Document" ("id", "name", "owner", "projectId", "createdAt", "updatedAt")
-VALUES ('doc-with-frecency-1', 'Doc With Frecency 1', 'macro|[email protected]', 'project-A', '2024-01-10 10:00:00', '2024-02-15 10:00:00'),
- ('doc-with-frecency-2', 'Doc With Frecency 2', 'macro|[email protected]', 'project-A', '2024-01-11 10:00:00', '2024-02-14 10:00:00'),
- ('doc-with-frecency-3', 'Doc With Frecency 3', 'macro|[email protected]', 'project-A', '2024-01-12 10:00:00', '2024-02-13 10:00:00');
+VALUES ('11111111-1111-1111-1111-111111111111', 'Doc With Frecency 1', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-01-10 10:00:00', '2024-02-15 10:00:00'),
+ ('22222222-2222-2222-2222-222222222222', 'Doc With Frecency 2', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-01-11 10:00:00', '2024-02-14 10:00:00'),
+ ('33333333-3333-3333-3333-333333333333', 'Doc With Frecency 3', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-01-12 10:00:00', '2024-02-13 10:00:00');
-- Documents WITHOUT frecency (should be returned)
INSERT INTO public."Document" ("id", "name", "owner", "projectId", "createdAt", "updatedAt")
-VALUES ('doc-no-frecency-1', 'Doc No Frecency 1', 'macro|[email protected]', 'project-A', '2024-01-13 10:00:00', '2024-02-12 10:00:00'),
- ('doc-no-frecency-2', 'Doc No Frecency 2', 'macro|[email protected]', 'project-A', '2024-01-14 10:00:00', '2024-02-11 10:00:00');
+VALUES ('44444444-4444-4444-4444-444444444444', 'Doc No Frecency 1', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-01-13 10:00:00', '2024-02-12 10:00:00'),
+ ('55555555-5555-5555-5555-555555555555', 'Doc No Frecency 2', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-01-14 10:00:00', '2024-02-11 10:00:00');
-- Create chats (2 with frecency, 2 without)
-- Chats WITH frecency (should be filtered out)
INSERT INTO public."Chat" ("id", "name", "userId", "projectId", "createdAt", "updatedAt")
-VALUES ('chat-with-frecency-1', 'Chat With Frecency 1', 'macro|[email protected]', 'project-A', '2024-01-15 10:00:00', '2024-02-10 10:00:00'),
- ('chat-with-frecency-2', 'Chat With Frecency 2', 'macro|[email protected]', 'project-A', '2024-01-16 10:00:00', '2024-02-09 10:00:00');
+VALUES ('66666666-6666-6666-6666-666666666666', 'Chat With Frecency 1', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-01-15 10:00:00', '2024-02-10 10:00:00'),
+ ('77777777-7777-7777-7777-777777777777', 'Chat With Frecency 2', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-01-16 10:00:00', '2024-02-09 10:00:00');
-- Chats WITHOUT frecency (should be returned)
INSERT INTO public."Chat" ("id", "name", "userId", "projectId", "createdAt", "updatedAt")
-VALUES ('chat-no-frecency-1', 'Chat No Frecency 1', 'macro|[email protected]', 'project-A', '2024-01-17 10:00:00', '2024-02-08 10:00:00'),
- ('chat-no-frecency-2', 'Chat No Frecency 2', 'macro|[email protected]', 'project-A', '2024-01-18 10:00:00', '2024-02-07 10:00:00');
+VALUES ('88888888-8888-8888-8888-888888888888', 'Chat No Frecency 1', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-01-17 10:00:00', '2024-02-08 10:00:00'),
+ ('99999999-9999-9999-9999-999999999999', 'Chat No Frecency 2', 'macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-01-18 10:00:00', '2024-02-07 10:00:00');
-- Dependencies for documents
INSERT INTO public."DocumentFamily" ("id", "rootDocumentId")
-VALUES (1, 'doc-with-frecency-1'),
- (2, 'doc-with-frecency-2'),
- (3, 'doc-with-frecency-3'),
- (4, 'doc-no-frecency-1'),
- (5, 'doc-no-frecency-2');
+VALUES (1, '11111111-1111-1111-1111-111111111111'),
+ (2, '22222222-2222-2222-2222-222222222222'),
+ (3, '33333333-3333-3333-3333-333333333333'),
+ (4, '44444444-4444-4444-4444-444444444444'),
+ (5, '55555555-5555-5555-5555-555555555555');
INSERT INTO public."DocumentInstance" ("id", "documentId", "sha")
-VALUES (1, 'doc-with-frecency-1', 'sha-1'),
- (2, 'doc-with-frecency-2', 'sha-2'),
- (3, 'doc-with-frecency-3', 'sha-3'),
- (4, 'doc-no-frecency-1', 'sha-4'),
- (5, 'doc-no-frecency-2', 'sha-5');
+VALUES (1, '11111111-1111-1111-1111-111111111111', 'sha-1'),
+ (2, '22222222-2222-2222-2222-222222222222', 'sha-2'),
+ (3, '33333333-3333-3333-3333-333333333333', 'sha-3'),
+ (4, '44444444-4444-4444-4444-444444444444', 'sha-4'),
+ (5, '55555555-5555-5555-5555-555555555555', 'sha-5');
-- User History entries for ordering tests
INSERT INTO public."UserHistory" ("userId", "itemId", "itemType", "updatedAt")
-VALUES ('macro|[email protected]', 'doc-no-frecency-1', 'document', '2024-03-15 10:00:00'),
- ('macro|[email protected]', 'doc-no-frecency-2', 'document', '2024-03-14 10:00:00'),
- ('macro|[email protected]', 'chat-no-frecency-1', 'chat', '2024-03-13 10:00:00'),
- ('macro|[email protected]', 'chat-no-frecency-2', 'chat', '2024-03-12 10:00:00'),
- ('macro|[email protected]', 'doc-with-frecency-1', 'document', '2024-03-11 10:00:00'),
- ('macro|[email protected]', 'doc-with-frecency-2', 'document', '2024-03-10 10:00:00'),
- ('macro|[email protected]', 'chat-with-frecency-1', 'chat', '2024-03-09 10:00:00');
+VALUES ('macro|[email protected]', '44444444-4444-4444-4444-444444444444', 'document', '2024-03-15 10:00:00'),
+ ('macro|[email protected]', '55555555-5555-5555-5555-555555555555', 'document', '2024-03-14 10:00:00'),
+ ('macro|[email protected]', '88888888-8888-8888-8888-888888888888', 'chat', '2024-03-13 10:00:00'),
+ ('macro|[email protected]', '99999999-9999-9999-9999-999999999999', 'chat', '2024-03-12 10:00:00'),
+ ('macro|[email protected]', '11111111-1111-1111-1111-111111111111', 'document', '2024-03-11 10:00:00'),
+ ('macro|[email protected]', '22222222-2222-2222-2222-222222222222', 'document', '2024-03-10 10:00:00'),
+ ('macro|[email protected]', '66666666-6666-6666-6666-666666666666', 'chat', '2024-03-09 10:00:00');
-- Insert frecency_aggregates for items WITH frecency
INSERT INTO public."frecency_aggregates" ("user_id", "entity_id", "entity_type", "frecency_score", "event_count", "first_event", "recent_events")
-VALUES ('macro|[email protected]', 'doc-with-frecency-1', 'document', 100.0, 10, '2024-01-10 10:00:00', '[]'::jsonb),
- ('macro|[email protected]', 'doc-with-frecency-2', 'document', 90.0, 8, '2024-01-11 10:00:00', '[]'::jsonb),
- ('macro|[email protected]', 'doc-with-frecency-3', 'document', 80.0, 6, '2024-01-12 10:00:00', '[]'::jsonb),
- ('macro|[email protected]', 'chat-with-frecency-1', 'chat', 70.0, 5, '2024-01-15 10:00:00', '[]'::jsonb),
- ('macro|[email protected]', 'chat-with-frecency-2', 'chat', 60.0, 4, '2024-01-16 10:00:00', '[]'::jsonb);
+VALUES ('macro|[email protected]', '11111111-1111-1111-1111-111111111111', 'document', 100.0, 10, '2024-01-10 10:00:00', '[]'::jsonb),
+ ('macro|[email protected]', '22222222-2222-2222-2222-222222222222', 'document', 90.0, 8, '2024-01-11 10:00:00', '[]'::jsonb),
+ ('macro|[email protected]', '33333333-3333-3333-3333-333333333333', 'document', 80.0, 6, '2024-01-12 10:00:00', '[]'::jsonb),
+ ('macro|[email protected]', '66666666-6666-6666-6666-666666666666', 'chat', 70.0, 5, '2024-01-15 10:00:00', '[]'::jsonb),
+ ('macro|[email protected]', '77777777-7777-7777-7777-777777777777', 'chat', 60.0, 4, '2024-01-16 10:00:00', '[]'::jsonb);
SET session_replication_role = 'origin';
diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rs
index b5e98f0271..900ebfed3e 100644
--- a/rust/cloud-storage/models_pagination/src/cursor.rs
+++ b/rust/cloud-storage/models_pagination/src/cursor.rs
@@ -381,6 +381,28 @@ impl<I, T: Sortable, F> Query<I, T, F> {
}
}
+ /// maps this filter type into another one via a callback fn.
+ /// This is analagous to [Option::map] over just the filter generic type
+ pub fn map_filter<Cb, F2>(self, cb: Cb) -> Query<I, T, F2>
+ where
+ Cb: FnOnce(F) -> F2,
+ {
+ match self {
+ Query::Sort(a, b) => Query::Sort(a, cb(b)),
+ Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter,
+ }) => Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter: cb(filter),
+ }),
+ }
+ }
+
/// returns the entity [Uuid] and [Sortable::Value] if they exist
pub fn vals(&self) -> (Option<&I>, Option<&T::Value>) {
match self {
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index 42e90e06b6..fdfe3aa122 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -179,18 +179,23 @@ where
async fn handle_frecency_cursor(
&self,
- #[expect(unused_variables)] from_value: Option<(f64, Option<EntityFilterAst>)>,
+ from_value: Option<(f64, Option<EntityFilterAst>)>,
soup_type: SoupType,
user: MacroUserIdStr<'static>,
limit: u16,
) -> Result<impl Iterator<Item = FrecencySoupItem>, SoupErr> {
+ let (from_score, filters) = match from_value {
+ None => (None, None),
+ Some((s, f)) => (Some(s), f),
+ };
+
let res = self
.frecency
.get_frecency_page(FrecencyPageRequest {
user_id: user.copied(),
- from_score: None,
+ from_score,
limit: limit as u32,
- filters: None,
+ filters,
})
.await?;
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index ab4be24f03..a085f7911a 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -91,14 +91,14 @@ async fn it_should_query_frecency() {
frecency_mock
.expect_get_top_entities()
.times(1)
- .withf(|user_id, limit| {
- assert_eq!(user_id.as_ref(), "macro|[email protected]");
- assert_eq!(*limit, 500);
+ .withf(|req| {
+ assert_eq!(req.user_id.as_ref(), "macro|[email protected]");
+ assert_eq!(req.limit, 500);
true
})
- .returning(|_user_id, limit| {
+ .returning(|req| {
Box::pin(async move {
- Ok((1..=limit)
+ Ok((1..=req.limit)
.map(|i| {
AggregateFrecency::new_mock(
EntityType::Document.with_entity_string(format!("my-document-{i}")),
@@ -159,14 +159,14 @@ async fn it_should_sort_frecency_descending() {
frecency_mock
.expect_get_top_entities()
.times(1)
- .withf(|user_id, limit| {
- assert_eq!(user_id.as_ref(), "macro|[email protected]");
- assert_eq!(*limit, 500);
+ .withf(|req| {
+ assert_eq!(req.user_id.as_ref(), "macro|[email protected]");
+ assert_eq!(req.limit, 500);
true
})
- .returning(|_user_id, limit| {
+ .returning(|req| {
Box::pin(async move {
- Ok((1..=limit)
+ Ok((1..=req.limit)
.map(|v| {
AggregateFrecency::new_mock(
EntityType::Document.with_entity_string(format!("my-document-{v}")),
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
index 90b77ebaf2..a3cfabe554 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
@@ -1,6 +1,9 @@
-use crate::domain::{
- models::{AdvancedSortParams, SimpleSortQuery, SimpleSortRequest},
- ports::SoupRepo,
+use crate::{
+ domain::{
+ models::{AdvancedSortParams, SimpleSortQuery, SimpleSortRequest},
+ ports::SoupRepo,
+ },
+ outbound::pg_soup_repo::expanded::dynamic::ExpandedDynamicCursorArgs,
};
use either::Either;
use models_soup::item::SoupItem;
@@ -27,15 +30,29 @@ impl SoupRepo for PgSoupRepo {
req: SimpleSortRequest<'a>,
) -> impl Future<Output = Result<Vec<SoupItem>, Self::Err>> + Send {
match req.cursor {
- SimpleSortQuery::ItemsAndFrecencyFilter(_) => {
- Either::Left(Either::Left(not_implemented(req)))
+ SimpleSortQuery::ItemsAndFrecencyFilter(query) => {
+ // Extract the EntityFilterAst from the tuple (Frecency, EntityFilterAst)
+ Either::Left(Either::Left(
+ expanded::dynamic::expanded_dynamic_cursor_soup(
+ &self.inner,
+ ExpandedDynamicCursorArgs {
+ user_id: req.user_id,
+ limit: req.limit,
+ cursor: query.map_filter(|(_, ast)| ast),
+ exclude_frecency: true,
+ },
+ ),
+ ))
}
SimpleSortQuery::ItemsFilter(ast) => Either::Left(Either::Right(
expanded::dynamic::expanded_dynamic_cursor_soup(
&self.inner,
- req.user_id,
- req.limit,
- ast,
+ ExpandedDynamicCursorArgs {
+ user_id: req.user_id,
+ limit: req.limit,
+ cursor: ast,
+ exclude_frecency: false,
+ },
),
)),
SimpleSortQuery::FilterFrecency(f) => Either::Right(Either::Left(
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
index 6037a8cc36..623e62284d 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
@@ -173,6 +173,22 @@ static SUFFIX: &str = r#"
LIMIT $3
"#;
+static SUFFIX_NO_FRECENCY: &str = r#"
+ SELECT Combined.* FROM Combined
+ LEFT JOIN frecency_aggregates fa
+ ON fa.entity_id = Combined."id"
+ AND fa.entity_type = Combined."item_type"
+ AND fa.user_id = $1
+ WHERE fa.id IS NULL
+ AND (
+ ($4::timestamptz IS NULL)
+ OR
+ (Combined."sort_ts", Combined."id") < ($4, $5)
+ )
+ ORDER BY Combined."sort_ts" DESC, Combined."updated_at" DESC
+ LIMIT $3
+"#;
+
fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>) -> String {
let Some(expr) = ast else {
return String::new();
@@ -240,7 +256,7 @@ fn build_project_filter(ast: Option<&Expr<ProjectLiteral>>) -> String {
}
}
-fn build_query(filter_ast: &EntityFilterAst) -> QueryBuilder<'_, Postgres> {
+fn build_query(filter_ast: &EntityFilterAst, exclude_frecency: bool) -> QueryBuilder<'_, Postgres> {
let mut builder = sqlx::QueryBuilder::new(PREFIX);
builder.push("Combined AS (");
@@ -265,7 +281,12 @@ fn build_query(filter_ast: &EntityFilterAst) -> QueryBuilder<'_, Postgres> {
));
builder.push(") ");
- builder.push(SUFFIX);
+
+ if exclude_frecency {
+ builder.push(SUFFIX_NO_FRECENCY);
+ } else {
+ builder.push(SUFFIX);
+ }
builder
}
@@ -406,18 +427,35 @@ impl SoupRow {
}
}
-#[tracing::instrument(skip(db, limit))]
-pub async fn expanded_dynamic_cursor_soup(
+#[derive(Debug)]
+pub(crate) struct ExpandedDynamicCursorArgs<'a> {
+ /// the user for which we are performing the query
+ pub user_id: MacroUserIdStr<'a>,
+ /// the limit of items we can return
+ pub limit: u16,
+ /// the Query that we are attempting to perform
+ pub cursor: Query<String, SimpleSortMethod, EntityFilterAst>,
+ /// whether or not the query should explicitly remove items that DO have
+ /// frecency records
+ pub exclude_frecency: bool,
+}
+
+#[tracing::instrument(skip(db), err)]
+pub(crate) async fn expanded_dynamic_cursor_soup(
db: &PgPool,
- user_id: MacroUserIdStr<'_>,
- limit: u16,
- cursor: Query<String, SimpleSortMethod, EntityFilterAst>,
+ args: ExpandedDynamicCursorArgs<'_>,
) -> Result<Vec<SoupItem>, sqlx::Error> {
+ let ExpandedDynamicCursorArgs {
+ user_id,
+ limit,
+ cursor,
+ exclude_frecency,
+ } = args;
let query_limit = limit as i64;
let sort_method_str = cursor.sort_method().to_string();
let (cursor_id, cursor_timestamp) = cursor.vals();
- build_query(cursor.filter())
+ build_query(cursor.filter(), exclude_frecency)
.build()
.bind(user_id.as_ref())
.bind(sort_method_str)
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
index 17744d04af..d2e92f6850 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
@@ -1,7 +1,7 @@
use crate::outbound::pg_soup_repo::expanded::{
by_cursor::{expanded_generic_cursor_soup, no_frecency_expanded_generic_soup},
by_ids::expanded_soup_by_ids,
- dynamic::expanded_dynamic_cursor_soup,
+ dynamic::{ExpandedDynamicCursorArgs, expanded_dynamic_cursor_soup},
};
use item_filters::ast::EntityFilterAst;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
@@ -439,11 +439,11 @@ async fn test_no_frecency_expanded_filters_out_frecency_items(
.collect();
let expected_ids: HashSet<String> = [
- "doc-no-frecency-1",
- "doc-no-frecency-2",
- "chat-no-frecency-1",
- "chat-no-frecency-2",
- "project-A",
+ "44444444-4444-4444-4444-444444444444", // doc-no-frecency-1
+ "55555555-5555-5555-5555-555555555555", // doc-no-frecency-2
+ "88888888-8888-8888-8888-888888888888", // chat-no-frecency-1
+ "99999999-9999-9999-9999-999999999999", // chat-no-frecency-2
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", // project-A
]
.iter()
.map(|&s| s.to_string())
@@ -456,11 +456,11 @@ async fn test_no_frecency_expanded_filters_out_frecency_items(
// Verify none of the frecency items are returned
let frecency_items = [
- "doc-with-frecency-1",
- "doc-with-frecency-2",
- "doc-with-frecency-3",
- "chat-with-frecency-1",
- "chat-with-frecency-2",
+ "11111111-1111-1111-1111-111111111111", // doc-with-frecency-1
+ "22222222-2222-2222-2222-222222222222", // doc-with-frecency-2
+ "33333333-3333-3333-3333-333333333333", // doc-with-frecency-3
+ "66666666-6666-6666-6666-666666666666", // chat-with-frecency-1
+ "77777777-7777-7777-7777-777777777777", // chat-with-frecency-2
];
for frecency_id in &frecency_items {
assert!(
@@ -512,11 +512,11 @@ async fn test_no_frecency_expanded_sorting_methods(pool: Pool<Postgres>) -> anyh
assert_eq!(
item_ids,
vec![
- "doc-no-frecency-1",
- "doc-no-frecency-2",
- "chat-no-frecency-1",
- "chat-no-frecency-2",
- "project-A"
+ "44444444-4444-4444-4444-444444444444", // doc-no-frecency-1
+ "55555555-5555-5555-5555-555555555555", // doc-no-frecency-2
+ "88888888-8888-8888-8888-888888888888", // chat-no-frecency-1
+ "99999999-9999-9999-9999-999999999999", // chat-no-frecency-2
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", // project-A
],
"Failed to sort correctly by UpdatedAt"
);
@@ -539,11 +539,11 @@ async fn test_no_frecency_expanded_sorting_methods(pool: Pool<Postgres>) -> anyh
assert_eq!(
item_ids,
vec![
- "chat-no-frecency-2",
- "chat-no-frecency-1",
- "doc-no-frecency-2",
- "doc-no-frecency-1",
- "project-A"
+ "99999999-9999-9999-9999-999999999999", // chat-no-frecency-2
+ "88888888-8888-8888-8888-888888888888", // chat-no-frecency-1
+ "55555555-5555-5555-5555-555555555555", // doc-no-frecency-2
+ "44444444-4444-4444-4444-444444444444", // doc-no-frecency-1
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", // project-A
],
"Failed to sort correctly by CreatedAt"
);
@@ -566,11 +566,11 @@ async fn test_no_frecency_expanded_sorting_methods(pool: Pool<Postgres>) -> anyh
assert_eq!(
item_ids,
vec![
- "doc-no-frecency-1",
- "doc-no-frecency-2",
- "chat-no-frecency-1",
- "chat-no-frecency-2",
- "project-A"
+ "44444444-4444-4444-4444-444444444444", // doc-no-frecency-1
+ "55555555-5555-5555-5555-555555555555", // doc-no-frecency-2
+ "88888888-8888-8888-8888-888888888888", // chat-no-frecency-1
+ "99999999-9999-9999-9999-999999999999", // chat-no-frecency-2
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", // project-A
],
"Failed to sort correctly by ViewedAt"
);
@@ -609,7 +609,7 @@ async fn test_no_frecency_expanded_cursor_pagination(pool: Pool<Postgres>) -> an
match &result.items[0] {
SoupItem::Document(doc) => {
assert_eq!(
- doc.id, "doc-no-frecency-1",
+ doc.id, "44444444-4444-4444-4444-444444444444",
"First item should be doc-no-frecency-1"
);
}
@@ -619,7 +619,7 @@ async fn test_no_frecency_expanded_cursor_pagination(pool: Pool<Postgres>) -> an
match &result.items[1] {
SoupItem::Document(doc) => {
assert_eq!(
- doc.id, "doc-no-frecency-2",
+ doc.id, "55555555-5555-5555-5555-555555555555",
"Second item should be doc-no-frecency-2"
);
}
@@ -645,7 +645,7 @@ async fn test_no_frecency_expanded_cursor_pagination(pool: Pool<Postgres>) -> an
match &items[0] {
SoupItem::Chat(chat) => {
assert_eq!(
- chat.id, "chat-no-frecency-1",
+ chat.id, "88888888-8888-8888-8888-888888888888",
"Third item should be chat-no-frecency-1"
);
}
@@ -655,7 +655,7 @@ async fn test_no_frecency_expanded_cursor_pagination(pool: Pool<Postgres>) -> an
match &items[1] {
SoupItem::Chat(chat) => {
assert_eq!(
- chat.id, "chat-no-frecency-2",
+ chat.id, "99999999-9999-9999-9999-999999999999",
"Fourth item should be chat-no-frecency-2"
);
}
@@ -676,9 +676,12 @@ async fn empty_ast_returns_same_as_static_query(db: PgPool) {
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let ast_res = expanded_dynamic_cursor_soup(
&db,
- user_id.clone(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, EntityFilterAst::mock_empty()),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.clone(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, EntityFilterAst::mock_empty()),
+ exclude_frecency: false,
+ },
)
.await
.unwrap();
@@ -743,9 +746,12 @@ async fn test_filter_by_document_file_type(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -812,9 +818,12 @@ async fn test_filter_by_document_ids(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -885,9 +894,12 @@ async fn test_filter_documents_by_project_id(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -953,9 +965,12 @@ async fn test_filter_chats_by_project_id(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1024,9 +1039,12 @@ async fn test_filter_by_chat_ids(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1097,9 +1115,12 @@ async fn test_filter_by_project_ids(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1184,9 +1205,12 @@ async fn test_combined_entity_filters(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1266,9 +1290,12 @@ async fn test_multiple_filter_criteria_documents(db: PgPool) -> anyhow::Result<(
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1340,9 +1367,12 @@ async fn test_filters_respect_access_control(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1401,9 +1431,12 @@ async fn test_filter_by_owner(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1463,9 +1496,12 @@ async fn test_filter_non_existent_items(db: PgPool) -> anyhow::Result<()> {
let items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 20,
- Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1522,9 +1558,12 @@ async fn test_cursor_pagination_with_document_filter(db: PgPool) -> anyhow::Resu
// First page - get 3 items
let result = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 3,
- Query::Sort(SimpleSortMethod::CreatedAt, filters.clone()),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 3,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters.clone()),
+ exclude_frecency: false,
+ },
)
.await?
.into_iter()
@@ -1553,14 +1592,17 @@ async fn test_cursor_pagination_with_document_filter(db: PgPool) -> anyhow::Resu
let second_page_items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 3,
- Query::Cursor(models_pagination::Cursor {
- id: cursor_decoded.id,
- limit: cursor_decoded.limit,
- val: cursor_decoded.val,
- filter: filters_for_cursor,
- }),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 3,
+ cursor: Query::Cursor(models_pagination::Cursor {
+ id: cursor_decoded.id,
+ limit: cursor_decoded.limit,
+ val: cursor_decoded.val,
+ filter: filters_for_cursor,
+ }),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1644,9 +1686,12 @@ async fn test_cursor_pagination_with_combined_filters(db: PgPool) -> anyhow::Res
// First page - get 2 items
let result = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 2,
- Query::Sort(SimpleSortMethod::CreatedAt, filters.clone()),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 2,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters.clone()),
+ exclude_frecency: false,
+ },
)
.await?
.into_iter()
@@ -1662,14 +1707,17 @@ async fn test_cursor_pagination_with_combined_filters(db: PgPool) -> anyhow::Res
let second_page_items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 2,
- Query::Cursor(models_pagination::Cursor {
- id: cursor_decoded.id,
- limit: cursor_decoded.limit,
- val: cursor_decoded.val,
- filter: filters_for_cursor,
- }),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 2,
+ cursor: Query::Cursor(models_pagination::Cursor {
+ id: cursor_decoded.id,
+ limit: cursor_decoded.limit,
+ val: cursor_decoded.val,
+ filter: filters_for_cursor,
+ }),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1733,11 +1781,19 @@ async fn test_cursor_pagination_filter_consistency(db: PgPool) -> anyhow::Result
let page_size: u16 = 2;
loop {
- let result = expanded_dynamic_cursor_soup(&db, user_id.copied(), page_size, current_query)
- .await?
- .into_iter()
- .paginate_on(page_size as usize, SimpleSortMethod::CreatedAt)
- .into_page();
+ let result = expanded_dynamic_cursor_soup(
+ &db,
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: page_size,
+ cursor: current_query,
+ exclude_frecency: false,
+ },
+ )
+ .await?
+ .into_iter()
+ .paginate_on(page_size as usize, SimpleSortMethod::CreatedAt)
+ .into_page();
all_items.extend(result.items);
@@ -1831,9 +1887,12 @@ async fn test_cursor_pagination_with_single_item_filter(db: PgPool) -> anyhow::R
// Get first page with limit 5
let result = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 5,
- Query::Sort(SimpleSortMethod::CreatedAt, filters.clone()),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 5,
+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters.clone()),
+ exclude_frecency: false,
+ },
)
.await?
.into_iter()
@@ -1854,14 +1913,17 @@ async fn test_cursor_pagination_with_single_item_filter(db: PgPool) -> anyhow::R
let second_page_items = expanded_dynamic_cursor_soup(
&db,
- user_id.copied(),
- 5,
- Query::Cursor(models_pagination::Cursor {
- id: cursor_decoded.id,
- limit: cursor_decoded.limit,
- val: cursor_decoded.val,
- filter: filters_for_cursor,
- }),
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 5,
+ cursor: Query::Cursor(models_pagination::Cursor {
+ id: cursor_decoded.id,
+ limit: cursor_decoded.limit,
+ val: cursor_decoded.val,
+ filter: filters_for_cursor,
+ }),
+ exclude_frecency: false,
+ },
)
.await?;
@@ -1887,3 +1949,142 @@ async fn test_cursor_pagination_with_single_item_filter(db: PgPool) -> anyhow::R
Ok(())
}
+
+// Test that exclude_frecency=true works together with AST filters
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("no_frecency_items")
+ )
+)]
+async fn test_dynamic_query_with_ast_and_frecency_exclusion(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ use item_filters::{ChatFilters, DocumentFilters, EntityFilters, ProjectFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Create an AST filter that only returns specific document IDs
+ // We'll filter for two docs without frecency and one with frecency
+ // We'll also filter out all chats and projects to isolate the document filtering
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec![
+ "44444444-4444-4444-4444-444444444444".to_string(), // doc-no-frecency-1
+ "55555555-5555-5555-5555-555555555555".to_string(), // doc-no-frecency-2
+ "11111111-1111-1111-1111-111111111111".to_string(), // doc-with-frecency-1
+ ],
+ ..Default::default()
+ },
+ // Filter out all chats by using a non-existent ID
+ chat_filters: ChatFilters {
+ chat_ids: vec!["00000000-0000-0000-0000-000000000000".to_string()],
+ ..Default::default()
+ },
+ // Filter out all projects by using a non-existent ID
+ project_filters: ProjectFilters {
+ project_ids: vec!["00000000-0000-0000-0000-000000000000".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ // Call with exclude_frecency=true
+ let items = expanded_dynamic_cursor_soup(
+ &pool,
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::UpdatedAt, filters.clone()),
+ exclude_frecency: true,
+ },
+ )
+ .await?;
+
+ // The no_frecency_items fixture has:
+ // - 44444444-4444-4444-4444-444444444444 (no frecency) - should be included
+ // - 55555555-5555-5555-5555-555555555555 (no frecency) - should be included
+ // - 11111111-1111-1111-1111-111111111111 (has frecency) - excluded by frecency filter
+ // So we should only get 2 documents
+ assert_eq!(
+ items.len(),
+ 2,
+ "Should return only documents without frecency that match the AST filter"
+ );
+
+ // Verify all returned items are documents
+ for item in &items {
+ assert!(
+ matches!(item, SoupItem::Document(_)),
+ "All returned items should be documents"
+ );
+ }
+
+ // Verify the returned document IDs
+ let returned_ids: HashSet<String> = items
+ .iter()
+ .map(|item| match item {
+ SoupItem::Document(d) => d.id.clone(),
+ _ => unreachable!(),
+ })
+ .collect();
+
+ let expected_ids: HashSet<String> = [
+ "44444444-4444-4444-4444-444444444444",
+ "55555555-5555-5555-5555-555555555555",
+ ]
+ .iter()
+ .map(|&s| s.to_string())
+ .collect();
+
+ assert_eq!(
+ returned_ids, expected_ids,
+ "Should only get documents without frecency records that match AST filter"
+ );
+
+ // Now test with exclude_frecency=false to verify both filters work independently
+ let items_with_frecency = expanded_dynamic_cursor_soup(
+ &pool,
+ ExpandedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 20,
+ cursor: Query::Sort(SimpleSortMethod::UpdatedAt, filters),
+ exclude_frecency: false,
+ },
+ )
+ .await?;
+
+ // Should get 3 documents (2 without frecency + 1 with frecency, all matching the AST filter)
+ assert_eq!(
+ items_with_frecency.len(),
+ 3,
+ "Should return all documents matching AST filter when frecency is not excluded"
+ );
+
+ let returned_with_frecency_ids: HashSet<String> = items_with_frecency
+ .iter()
+ .map(|item| match item {
+ SoupItem::Document(d) => d.id.clone(),
+ _ => unreachable!(),
+ })
+ .collect();
+
+ let expected_with_frecency_ids: HashSet<String> = [
+ "44444444-4444-4444-4444-444444444444",
+ "55555555-5555-5555-5555-555555555555",
+ "11111111-1111-1111-1111-111111111111",
+ ]
+ .iter()
+ .map(|&s| s.to_string())
+ .collect();
+
+ assert_eq!(
+ returned_with_frecency_ids, expected_with_frecency_ids,
+ "Should get all documents matching AST filter regardless of frecency"
+ );
+
+ Ok(())
+}