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.

fix(soup): group by query bugs (#3419)

dev-rbb8004f563679
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
index 8586d2369c..00f7123f83 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
@@ -135,11 +135,7 @@ export const SoupViewContextProvider: FlowComponent<
: 'created_at';
return {
- // When doing a group by query, the limit will end up cutting off groups.
- // So, instead we increase the fetch limit for the group by query to make
- // sure we get as many groups as we can. Alternative would be to implement
- // paginated loading of groups, but we dont have that right now.
- limit: soup.grouping.activeGroupId() ? 2_000 : 100,
+ limit: 100,
sort_method: sortMethod,
};
});
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
index 133e8b7757..6b100eb562 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
@@ -82,7 +82,7 @@ import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { isMobile } from '@core/mobile/isMobile';
import { useDisplayName } from '@core/user/displayName';
-import type { MacroId } from '@core/user/macroId';
+import { type MacroId, tryMacroId } from '@core/user/macroId';
import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
import {
type EntityData,
@@ -133,22 +133,7 @@ import { SoupEntitySelectionToolbar } from './soup-entity-selection-toolbar';
import { useSoupNavigationHotkeys } from './use-soup-navigation-hotkeys';
import { useSoupViewHotkeys } from './use-soup-view-hotkeys';
-// Property values for entity-reference properties (e.g. assignees) are stored
-// as `{"entity_id": "...", "entity_type": "USER"}` and arrive in group keys as
-// the JSON-encoded text of that object.
-const parseEntityRefId = (key: string): string | null => {
- try {
- const parsed: unknown = JSON.parse(key);
- if (typeof parsed === 'string') return parsed;
- if (typeof parsed !== 'object' || parsed === null) return null;
- const id = (parsed as Record<string, unknown>).entity_id;
- return typeof id === 'string' ? id : null;
- } catch {
- return null;
- }
-};
-
-const SoupSectionHeader = (props: {
+export const SoupSectionHeader = (props: {
children: JSX.Element;
onClick?: () => void;
highlighted?: boolean;
@@ -203,9 +188,9 @@ const DefaultGroupHeader = (
field.propertyDefinitionId !== SYSTEM_PROPERTY_IDS.ASSIGNEES ||
props.group.key === ''
) {
- return null;
+ return;
}
- return parseEntityRefId(props.group.key);
+ return tryMacroId(props.group.key);
});
return (
@@ -236,7 +221,7 @@ const DefaultGroupHeader = (
>
{(id) => (
<AssigneeGroupContent
- assigneeId={id() as MacroId}
+ assigneeId={id()}
fallbackLabel={props.group.label}
/>
)}
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 1f10db5a94..d7c29da690 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
@@ -1763,7 +1763,15 @@ fn build_grouped_query<'a>(
builder.push("\"group_key\"");
}
}
- builder.push(", \"sort_ts\" DESC, \"id\" DESC LIMIT $3");
+ builder.push(", \"sort_ts\" DESC, \"id\" DESC");
+
+ // Apply LIMIT only in single-group "load more" mode. In multi-group mode the
+ // result is already bounded by the per-group cap inside FilteredGroupedItems
+ // (PER_GROUP_LIMIT), so a row-level LIMIT here would silently drop entire
+ // groups from the response when there are many groups.
+ if grouping.group_key.is_some() {
+ builder.push(" LIMIT $3");
+ }
(builder, entity_type_bind)
}
@@ -1793,6 +1801,7 @@ pub async fn expanded_dynamic_cursor_soup_grouped(
let (mut query_builder, entity_type_bind) =
build_grouped_query(cursor.filter(), exclude_frecency, &grouping);
+ // $9 is bound unconditionally (NULL when not in single-group mode) so $10 stays aligned.
let mut query = query_builder
.build()
.bind(user_id.as_ref())
@@ -1802,12 +1811,8 @@ pub async fn expanded_dynamic_cursor_soup_grouped(
.bind(cursor_id_str)
.bind(completed_option_id)
.bind(status_property_id)
- .bind(assignees_property_id);
-
- // Bind group_key as $9 when filtering by specific group
- if let Some(ref key) = grouping.group_key {
- query = query.bind(key.clone());
- }
+ .bind(assignees_property_id)
+ .bind(grouping.group_key.clone());
// Bind entity_type as $10 when property grouping with entity_type filter
if let Some(ref et) = entity_type_bind {
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping.rs
index 4c29009670..f486adcb79 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping.rs
@@ -9,11 +9,17 @@ pub fn group_select_expr(field: &GroupByField) -> Cow<'static, str> {
GroupByField::Date => Cow::Owned(date_bucket_sql_key("sort_ts")),
GroupByField::EntityType => Cow::Borrowed("item_type"),
GroupByField::Project => Cow::Borrowed("COALESCE(project_id::text, '')"),
- GroupByField::Property { .. } => {
- // For select options, value is an array of UUIDs like ["uuid1", "uuid2"]
- // Extract the first element as text
- Cow::Borrowed("COALESCE(ep_group.values->'value'->>0, '')")
- }
+ GroupByField::Property { .. } => Cow::Borrowed(
+ "COALESCE(
+ CASE ep_group.values->>'type'
+ WHEN 'EntityReference' THEN ep_group.val->>'entity_id'
+ WHEN 'SelectOption' THEN ep_group.val#>>'{}'
+ WHEN 'Link' THEN ep_group.val#>>'{}'
+ ELSE NULL
+ END,
+ ''
+ )",
+ ),
}
}
@@ -23,25 +29,37 @@ pub fn group_order_expr(field: &GroupByField) -> Cow<'static, str> {
GroupByField::Date => Cow::Owned(date_bucket_sql_order("sort_ts")),
GroupByField::EntityType => Cow::Borrowed("item_type"),
GroupByField::Project => Cow::Borrowed("project_id NULLS LAST"),
- GroupByField::Property { .. } => {
- // values->'value' is an array of UUID strings, extract first and lookup display_order
- Cow::Borrowed(
- "COALESCE((SELECT po.display_order FROM property_options po WHERE po.id::text = (ep_group.values->'value'->>0)), 999999)",
- )
- }
+ GroupByField::Property { .. } => Cow::Borrowed(
+ "COALESCE(
+ (SELECT po.display_order FROM property_options po
+ WHERE po.id::text =
+ CASE ep_group.values->>'type'
+ WHEN 'SelectOption' THEN ep_group.val#>>'{}'
+ ELSE NULL
+ END),
+ 999999
+ )",
+ ),
}
}
/// Result of building a group JOIN clause with optional bind parameter.
pub struct GroupJoinClause {
- /// The SQL JOIN clause (may contain $10 placeholder for entity_type)
+ /// The SQL JOIN clause (may contain `$10` placeholder for entity_type).
+ /// Callers must ensure the entity_type value is bound at $10 (and that $9
+ /// is bound — with `group_key` or NULL — so the indices line up).
pub sql: String,
- /// Entity type value to bind at $10, if present
+ /// Entity type value to bind at `$10`, if present
pub entity_type_bind: Option<String>,
}
/// Build the JOIN clause for property-based grouping.
-/// Returns SQL with $10 placeholder for entity_type when present.
+/// Returns SQL with `$10` placeholder for entity_type when present.
+///
+/// The clause LATERAL-expands `entity_properties.values->'value'` into one row
+/// per element, so multi-value properties (e.g. assignees) place each item into
+/// every group it belongs to. Items without a matching row, or with an empty
+/// array / scalar value, produce a single row with NULL `val` (→ "Not Set").
pub fn group_join_clause(field: &GroupByField) -> Option<GroupJoinClause> {
match field {
GroupByField::Property {
@@ -49,16 +67,25 @@ pub fn group_join_clause(field: &GroupByField) -> Option<GroupJoinClause> {
entity_type,
} => {
let (entity_type_filter, entity_type_bind) = match entity_type {
- Some(et) => (
- "AND ep_group.entity_type = $10".to_string(),
- Some(et.clone()),
- ),
+ Some(et) => ("AND ep.entity_type = $10".to_string(), Some(et.clone())),
None => (String::new(), None),
};
Some(GroupJoinClause {
sql: format!(
- "LEFT JOIN entity_properties ep_group ON ep_group.entity_id = t.id::text AND ep_group.property_definition_id = '{}' {}",
+ "LEFT JOIN LATERAL (
+ SELECT ep.values, elem.val
+ FROM entity_properties ep
+ LEFT JOIN LATERAL jsonb_array_elements(
+ CASE WHEN jsonb_typeof(ep.values->'value') = 'array'
+ THEN ep.values->'value'
+ ELSE '[]'::jsonb
+ END
+ ) elem(val) ON TRUE
+ WHERE ep.entity_id = t.id::text
+ AND ep.property_definition_id = '{}'
+ {}
+ ) ep_group ON TRUE",
property_definition_id, entity_type_filter
),
entity_type_bind,