Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix: search items stability (#534)
gbirmana228f8765579
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 5344e95fe1..18fb636984 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -7534,6 +7534,7 @@ dependencies = ["email_service_client","futures","http-body-util",+ "indexmap 2.7.1","item_filters","macro_auth","macro_cors",diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.tomlindex 8135a13e90..6666cf5af7 100644--- a/rust/cloud-storage/search_service/Cargo.toml+++ b/rust/cloud-storage/search_service/Cargo.toml@@ -14,6 +14,7 @@ comms_service_client = { path = "../comms_service_client" }document_storage_service_client = { path = "../document_storage_service_client" }email_service_client = { path = "../email_service_client" }futures = { workspace = true }+indexmap = "2"http-body-util = { workspace = true }macro_auth = { path = "../macro_auth" }macro_db_client = { path = "../macro_db_client" }diff --git a/rust/cloud-storage/search_service/src/api/search/channel.rs b/rust/cloud-storage/search_service/src/api/search/channel.rsindex 9be14aaf00..066803104f 100644--- a/rust/cloud-storage/search_service/src/api/search/channel.rs+++ b/rust/cloud-storage/search_service/src/api/search/channel.rs@@ -1,4 +1,5 @@use crate::api::search::simple::{SearchError, simple_channel::search_channels};+use indexmap::IndexMap;use std::collections::HashMap;use super::SearchPaginationParams;@@ -116,8 +117,8 @@ pub fn construct_search_result(search_results: Vec<opensearch_client::search::model::SearchHit>,channel_histories: HashMap<Uuid, ChannelHistoryInfo>,) -> anyhow::Result<Vec<ChannelSearchResponseItemWithMetadata>> {- // construct entity hit map of id -> vec<hits>- let entity_id_hit_map: HashMap<sqlx::types::Uuid, Vec<ChannelSearchResult>> = search_results+ // construct entity hit map of id -> vec<hits> using IndexMap to preserve insertion order+ let entity_id_hit_map: IndexMap<sqlx::types::Uuid, Vec<ChannelSearchResult>> = search_results.into_iter().map(|hit| {let result = if let Some(SearchGotoContent::Channels(goto)) = hit.goto {@@ -144,12 +145,12 @@ pub fn construct_search_result(};(hit.entity_id.parse().unwrap(), result)})- .fold(HashMap::new(), |mut map, (entity_id, result)| {+ .fold(IndexMap::new(), |mut map, (entity_id, result)| {map.entry(entity_id).or_insert_with(Vec::new).push(result);map});- // now construct the search results+ // now construct the search results in the original search result orderlet result: Vec<ChannelSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter().filter_map(|(entity_id, hits)| {diff --git a/rust/cloud-storage/search_service/src/api/search/channel/test.rs b/rust/cloud-storage/search_service/src/api/search/channel/test.rsindex 1061308eef..ed8c1d14c0 100644--- a/rust/cloud-storage/search_service/src/api/search/channel/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/channel/test.rs@@ -364,3 +364,146 @@ fn test_channel_history_null_viewed_at() {assert!(metadata.viewed_at.is_none());assert!(metadata.interacted_at.is_none());}++#[test]+fn test_sort_stability() {+ let channel_ids = [+ "550e8400-e29b-41d4-a716-446655440003",+ "550e8400-e29b-41d4-a716-446655440001",+ "550e8400-e29b-41d4-a716-446655440005",+ "550e8400-e29b-41d4-a716-446655440002",+ "550e8400-e29b-41d4-a716-446655440004",+ ];++ let input = vec![+ opensearch_client::search::model::SearchHit {+ entity_id: channel_ids[0].to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg3".to_string(),+ created_at: 1234567890,+ updated_at: 1234567891,+ thread_id: Some("thread3".to_string()),+ sender_id: "user1".to_string(),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["third".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: channel_ids[1].to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg1".to_string(),+ created_at: 1234567890,+ updated_at: 1234567891,+ thread_id: Some("thread1".to_string()),+ sender_id: "user1".to_string(),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["first".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: channel_ids[2].to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg5".to_string(),+ created_at: 1234567890,+ updated_at: 1234567891,+ thread_id: Some("thread5".to_string()),+ sender_id: "user1".to_string(),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["fifth".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: channel_ids[3].to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg2".to_string(),+ created_at: 1234567890,+ updated_at: 1234567891,+ thread_id: Some("thread2".to_string()),+ sender_id: "user1".to_string(),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["second".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: channel_ids[4].to_string(),+ entity_type: SearchEntityType::Channels,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: "msg4".to_string(),+ created_at: 1234567890,+ updated_at: 1234567891,+ thread_id: Some("thread4".to_string()),+ sender_id: "user1".to_string(),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["fourth".to_string()],+ },+ },+ ];++ let mut channel_histories = HashMap::new();+ for channel_id in &channel_ids {+ channel_histories.insert(+ Uuid::parse_str(channel_id).unwrap(),+ create_channel_history(channel_id),+ );+ }++ let result1 = construct_search_result(input.clone(), channel_histories.clone()).unwrap();+ let result2 = construct_search_result(input.clone(), channel_histories.clone()).unwrap();+ let result3 = construct_search_result(input.clone(), channel_histories.clone()).unwrap();++ assert_eq!(result1.len(), 5);+ assert_eq!(result2.len(), 5);+ assert_eq!(result3.len(), 5);++ let ids1: Vec<String> = result1.iter().map(|r| r.extra.id.clone()).collect();+ let ids2: Vec<String> = result2.iter().map(|r| r.extra.id.clone()).collect();+ let ids3: Vec<String> = result3.iter().map(|r| r.extra.id.clone()).collect();++ assert_eq!(ids1, ids2, "Results should be stable between runs");+ assert_eq!(ids2, ids3, "Results should be stable between runs");++ assert_eq!(+ ids1,+ channel_ids.to_vec(),+ "Results should preserve original search result order"+ );+}diff --git a/rust/cloud-storage/search_service/src/api/search/chat.rs b/rust/cloud-storage/search_service/src/api/search/chat.rsindex f9d6a85c8e..e6289f17c0 100644--- a/rust/cloud-storage/search_service/src/api/search/chat.rs+++ b/rust/cloud-storage/search_service/src/api/search/chat.rs@@ -7,6 +7,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};+use indexmap::IndexMap;use model::{response::ErrorResponse, user::UserContext};use models_search::chat::{ChatMessageSearchResult, ChatSearchRequest, ChatSearchResponse, ChatSearchResponseItem,@@ -98,8 +99,8 @@ pub fn construct_search_result(search_results: Vec<opensearch_client::search::model::SearchHit>,chat_histories: HashMap<String, macro_db_client::chat::get::ChatHistoryInfo>,) -> anyhow::Result<Vec<ChatSearchResponseItemWithMetadata>> {- // construct entity hit map of id -> vec<hits>- let entity_id_hit_map: HashMap<String, Vec<ChatMessageSearchResult>> = search_results+ // construct entity hit map of id -> vec<hits> using IndexMap to preserve insertion order+ let entity_id_hit_map: IndexMap<String, Vec<ChatMessageSearchResult>> = search_results.into_iter().map(|hit| {let result = if let Some(SearchGotoContent::Chats(goto)) = hit.goto {@@ -120,12 +121,12 @@ pub fn construct_search_result(};(hit.entity_id, result)})- .fold(HashMap::new(), |mut map, (entity_id, result)| {+ .fold(IndexMap::new(), |mut map, (entity_id, result)| {map.entry(entity_id).or_insert_with(Vec::new).push(result);map});- // now construct the search results+ // now construct the search results in the original search result orderlet result: Vec<ChatSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter().filter_map(|(entity_id, hits)| {diff --git a/rust/cloud-storage/search_service/src/api/search/chat/test.rs b/rust/cloud-storage/search_service/src/api/search/chat/test.rsindex 7abccad52a..87e69686b7 100644--- a/rust/cloud-storage/search_service/src/api/search/chat/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/chat/test.rs@@ -375,3 +375,40 @@ fn test_chat_history_null_viewed_at() {);assert!(result[0].metadata.as_ref().unwrap().viewed_at.is_none());}++#[test]+fn test_sort_stability() {+ let input = vec![+ create_test_response("chat_3", "msg_3", Some(vec!["third".to_string()])),+ create_test_response("chat_1", "msg_1", Some(vec!["first".to_string()])),+ create_test_response("chat_5", "msg_5", Some(vec!["fifth".to_string()])),+ create_test_response("chat_2", "msg_2", Some(vec!["second".to_string()])),+ create_test_response("chat_4", "msg_4", Some(vec!["fourth".to_string()])),+ ];++ let mut chat_histories = HashMap::new();+ for chat_id in ["chat_1", "chat_2", "chat_3", "chat_4", "chat_5"] {+ chat_histories.insert(chat_id.to_string(), create_chat_history(chat_id));+ }++ let result1 = construct_search_result(input.clone(), chat_histories.clone()).unwrap();+ let result2 = construct_search_result(input.clone(), chat_histories.clone()).unwrap();+ let result3 = construct_search_result(input.clone(), chat_histories.clone()).unwrap();++ assert_eq!(result1.len(), 5);+ assert_eq!(result2.len(), 5);+ assert_eq!(result3.len(), 5);++ let ids1: Vec<String> = result1.iter().map(|r| r.extra.id.clone()).collect();+ let ids2: Vec<String> = result2.iter().map(|r| r.extra.id.clone()).collect();+ let ids3: Vec<String> = result3.iter().map(|r| r.extra.id.clone()).collect();++ assert_eq!(ids1, ids2, "Results should be stable between runs");+ assert_eq!(ids2, ids3, "Results should be stable between runs");++ assert_eq!(+ ids1,+ vec!["chat_3", "chat_1", "chat_5", "chat_2", "chat_4"],+ "Results should preserve original search result order"+ );+}diff --git a/rust/cloud-storage/search_service/src/api/search/document.rs b/rust/cloud-storage/search_service/src/api/search/document.rsindex d6c0de5ee1..e19a174205 100644--- a/rust/cloud-storage/search_service/src/api/search/document.rs+++ b/rust/cloud-storage/search_service/src/api/search/document.rs@@ -5,6 +5,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};+use indexmap::IndexMap;use model::{response::ErrorResponse, user::UserContext};use models_opensearch::SearchEntityType;use models_search::document::{@@ -105,8 +106,8 @@ pub fn construct_search_result(macro_db_client::document::get_document_history::DocumentHistoryInfo,>,) -> anyhow::Result<Vec<DocumentSearchResponseItemWithMetadata>> {- // construct entity hit map of id -> vec<hits>- let entity_id_hit_map: HashMap<String, Vec<DocumentSearchResult>> = search_results+ // construct entity hit map of id -> vec<hits> using IndexMap to preserve insertion order+ let entity_id_hit_map: IndexMap<String, Vec<DocumentSearchResult>> = search_results.into_iter().map(|hit| {let result = if let Some(SearchGotoContent::Documents(goto)) = hit.goto {@@ -127,12 +128,12 @@ pub fn construct_search_result(};(hit.entity_id, result)})- .fold(HashMap::new(), |mut map, (entity_id, result)| {+ .fold(IndexMap::new(), |mut map, (entity_id, result)| {map.entry(entity_id).or_insert_with(Vec::new).push(result);map});- // now construct the search results+ // now construct the search results in the original search result orderlet result: Vec<DocumentSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter().filter_map(|(entity_id, hits)| {diff --git a/rust/cloud-storage/search_service/src/api/search/document/test.rs b/rust/cloud-storage/search_service/src/api/search/document/test.rsindex 50afaad2a6..d42279f6e4 100644--- a/rust/cloud-storage/search_service/src/api/search/document/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/document/test.rs@@ -447,3 +447,135 @@ fn test_document_history_deleted() {// Document not in DB should not be returnedassert_eq!(result_not_found.len(), 0);}++#[test]+fn test_sort_stability() {+ let input = vec![+ opensearch_client::search::model::SearchHit {+ entity_id: "doc_3".to_string(),+ entity_type: SearchEntityType::Documents,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Documents(+ opensearch_client::search::model::SearchGotoDocument {+ node_id: "node_3".to_string(),+ raw_content: Some("third".to_string()),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["third".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: "doc_1".to_string(),+ entity_type: SearchEntityType::Documents,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Documents(+ opensearch_client::search::model::SearchGotoDocument {+ node_id: "node_1".to_string(),+ raw_content: Some("first".to_string()),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["first".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: "doc_5".to_string(),+ entity_type: SearchEntityType::Documents,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Documents(+ opensearch_client::search::model::SearchGotoDocument {+ node_id: "node_5".to_string(),+ raw_content: Some("fifth".to_string()),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["fifth".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: "doc_2".to_string(),+ entity_type: SearchEntityType::Documents,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Documents(+ opensearch_client::search::model::SearchGotoDocument {+ node_id: "node_2".to_string(),+ raw_content: Some("second".to_string()),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["second".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: "doc_4".to_string(),+ entity_type: SearchEntityType::Documents,+ goto: Some(+ opensearch_client::search::model::SearchGotoContent::Documents(+ opensearch_client::search::model::SearchGotoDocument {+ node_id: "node_4".to_string(),+ raw_content: Some("fourth".to_string()),+ },+ ),+ ),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["fourth".to_string()],+ },+ },+ ];++ let mut document_histories = HashMap::new();+ let now = chrono::Utc::now();+ for doc_id in ["doc_1", "doc_2", "doc_3", "doc_4", "doc_5"] {+ document_histories.insert(+ doc_id.to_string(),+ DocumentHistoryInfo {+ item_id: doc_id.to_string(),+ created_at: now,+ updated_at: now,+ viewed_at: None,+ project_id: None,+ file_type: Some("pdf".to_string()),+ file_name: format!("{}.pdf", doc_id),+ owner: "user1".to_string(),+ deleted_at: None,+ sub_type: None,+ },+ );+ }++ let result1 = construct_search_result(input.clone(), document_histories.clone()).unwrap();+ let result2 = construct_search_result(input.clone(), document_histories.clone()).unwrap();+ let result3 = construct_search_result(input.clone(), document_histories.clone()).unwrap();++ assert_eq!(result1.len(), 5);+ assert_eq!(result2.len(), 5);+ assert_eq!(result3.len(), 5);++ let ids1: Vec<String> = result1.iter().map(|r| r.extra.id.clone()).collect();+ let ids2: Vec<String> = result2.iter().map(|r| r.extra.id.clone()).collect();+ let ids3: Vec<String> = result3.iter().map(|r| r.extra.id.clone()).collect();++ assert_eq!(ids1, ids2, "Results should be stable between runs");+ assert_eq!(ids2, ids3, "Results should be stable between runs");++ assert_eq!(+ ids1,+ vec!["doc_3", "doc_1", "doc_5", "doc_2", "doc_4"],+ "Results should preserve original search result order"+ );+}diff --git a/rust/cloud-storage/search_service/src/api/search/email.rs b/rust/cloud-storage/search_service/src/api/search/email.rsindex c7d2528d4a..cd048c9e21 100644--- a/rust/cloud-storage/search_service/src/api/search/email.rs+++ b/rust/cloud-storage/search_service/src/api/search/email.rs@@ -7,6 +7,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};+use indexmap::IndexMap;use model::{response::ErrorResponse, user::UserContext};use models_email::service::message::{ThreadHistoryInfo, ThreadHistoryRequest};use models_search::email::{@@ -117,8 +118,8 @@ pub fn construct_search_result(search_results: Vec<opensearch_client::search::model::SearchHit>,thread_histories: HashMap<Uuid, ThreadHistoryInfo>,) -> anyhow::Result<Vec<EmailSearchResponseItemWithMetadata>> {- // construct entity hit map of id -> vec<hits>- let entity_id_hit_map: HashMap<Uuid, Vec<EmailSearchResult>> = search_results+ // construct entity hit map of id -> vec<hits> using IndexMap to preserve insertion order+ let entity_id_hit_map: IndexMap<Uuid, Vec<EmailSearchResult>> = search_results.into_iter().map(|hit| {let result = if let Some(SearchGotoContent::Emails(goto)) = hit.goto {@@ -149,12 +150,12 @@ pub fn construct_search_result(};(hit.entity_id.parse().unwrap(), result)})- .fold(HashMap::new(), |mut map, (entity_id, result)| {+ .fold(IndexMap::new(), |mut map, (entity_id, result)| {map.entry(entity_id).or_insert_with(Vec::new).push(result);map});- // now construct the search results+ // now construct the search results in the original search result orderlet result: Vec<EmailSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter().filter_map(|(entity_id, hits)| {diff --git a/rust/cloud-storage/search_service/src/api/search/email/test.rs b/rust/cloud-storage/search_service/src/api/search/email/test.rsindex d84b9f2e3a..4223cde8e4 100644--- a/rust/cloud-storage/search_service/src/api/search/email/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/email/test.rs@@ -69,3 +69,146 @@ fn test_construct_search_result_single_thread() {);assert_eq!(result[0].extra.subject, Some("subject".to_string()));}++#[test]+fn test_sort_stability() {+ let thread_ids = [+ "550e8400-e29b-41d4-a716-446655440003",+ "550e8400-e29b-41d4-a716-446655440001",+ "550e8400-e29b-41d4-a716-446655440005",+ "550e8400-e29b-41d4-a716-446655440002",+ "550e8400-e29b-41d4-a716-446655440004",+ ];++ let input = vec![+ opensearch_client::search::model::SearchHit {+ entity_id: thread_ids[0].to_string(),+ entity_type: SearchEntityType::Emails,+ goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(+ opensearch_client::search::model::SearchGotoEmail {+ email_message_id: "msg3".to_string(),+ sender: "[email protected]".to_string(),+ recipients: vec!["[email protected]".to_string()],+ cc: vec![],+ bcc: vec![],+ labels: vec!["inbox".to_string()],+ sent_at: Some(1234567800),+ },+ )),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["third".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: thread_ids[1].to_string(),+ entity_type: SearchEntityType::Emails,+ goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(+ opensearch_client::search::model::SearchGotoEmail {+ email_message_id: "msg1".to_string(),+ sender: "[email protected]".to_string(),+ recipients: vec!["[email protected]".to_string()],+ cc: vec![],+ bcc: vec![],+ labels: vec!["inbox".to_string()],+ sent_at: Some(1234567800),+ },+ )),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["first".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: thread_ids[2].to_string(),+ entity_type: SearchEntityType::Emails,+ goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(+ opensearch_client::search::model::SearchGotoEmail {+ email_message_id: "msg5".to_string(),+ sender: "[email protected]".to_string(),+ recipients: vec!["[email protected]".to_string()],+ cc: vec![],+ bcc: vec![],+ labels: vec!["inbox".to_string()],+ sent_at: Some(1234567800),+ },+ )),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["fifth".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: thread_ids[3].to_string(),+ entity_type: SearchEntityType::Emails,+ goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(+ opensearch_client::search::model::SearchGotoEmail {+ email_message_id: "msg2".to_string(),+ sender: "[email protected]".to_string(),+ recipients: vec!["[email protected]".to_string()],+ cc: vec![],+ bcc: vec![],+ labels: vec!["inbox".to_string()],+ sent_at: Some(1234567800),+ },+ )),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["second".to_string()],+ },+ },+ opensearch_client::search::model::SearchHit {+ entity_id: thread_ids[4].to_string(),+ entity_type: SearchEntityType::Emails,+ goto: Some(opensearch_client::search::model::SearchGotoContent::Emails(+ opensearch_client::search::model::SearchGotoEmail {+ email_message_id: "msg4".to_string(),+ sender: "[email protected]".to_string(),+ recipients: vec!["[email protected]".to_string()],+ cc: vec![],+ bcc: vec![],+ labels: vec!["inbox".to_string()],+ sent_at: Some(1234567800),+ },+ )),+ score: None,+ highlight: Highlight {+ name: None,+ content: vec!["fourth".to_string()],+ },+ },+ ];++ let mut thread_histories = HashMap::new();+ for thread_id in &thread_ids {+ thread_histories.insert(+ Uuid::parse_str(thread_id).unwrap(),+ create_email_history(thread_id),+ );+ }++ let result1 = construct_search_result(input.clone(), thread_histories.clone()).unwrap();+ let result2 = construct_search_result(input.clone(), thread_histories.clone()).unwrap();+ let result3 = construct_search_result(input.clone(), thread_histories.clone()).unwrap();++ assert_eq!(result1.len(), 5);+ assert_eq!(result2.len(), 5);+ assert_eq!(result3.len(), 5);++ let ids1: Vec<String> = result1.iter().map(|r| r.extra.id.clone()).collect();+ let ids2: Vec<String> = result2.iter().map(|r| r.extra.id.clone()).collect();+ let ids3: Vec<String> = result3.iter().map(|r| r.extra.id.clone()).collect();++ assert_eq!(ids1, ids2, "Results should be stable between runs");+ assert_eq!(ids2, ids3, "Results should be stable between runs");++ assert_eq!(+ ids1,+ thread_ids.to_vec(),+ "Results should preserve original search result order"+ );+}diff --git a/rust/cloud-storage/search_service/src/api/search/project.rs b/rust/cloud-storage/search_service/src/api/search/project.rsindex 2c38f1f780..f02c7fc7d4 100644--- a/rust/cloud-storage/search_service/src/api/search/project.rs+++ b/rust/cloud-storage/search_service/src/api/search/project.rs@@ -5,6 +5,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Json, Response},};+use indexmap::IndexMap;use model::{response::ErrorResponse, user::UserContext};use models_search::project::{ProjectSearchRequest, ProjectSearchResponse, ProjectSearchResponseItem,@@ -105,8 +106,8 @@ pub fn construct_search_result(macro_db_client::projects::get_project_history::ProjectHistoryInfo,>,) -> anyhow::Result<Vec<ProjectSearchResponseItemWithMetadata>> {- // construct entity hit map of id -> vec<hits>- let entity_id_hit_map: HashMap<String, Vec<ProjectSearchResult>> = search_results+ // construct entity hit map of id -> vec<hits> using IndexMap to preserve insertion order+ let entity_id_hit_map: IndexMap<String, Vec<ProjectSearchResult>> = search_results.into_iter().map(|hit| {let result = ProjectSearchResult {@@ -116,12 +117,12 @@ pub fn construct_search_result((hit.entity_id, result)})- .fold(HashMap::new(), |mut map, (entity_id, result)| {+ .fold(IndexMap::new(), |mut map, (entity_id, result)| {map.entry(entity_id).or_insert_with(Vec::new).push(result);map});- // now construct the search results+ // now construct the search results in the original search result orderlet result: Vec<ProjectSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter().filter_map(|(entity_id, hits)| {