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.

Seanaye/feat/channel filter projections (#6362)

Sean Aye352924c5d5b0
diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/notification-projection-harness.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/notification-projection-harness.ts
index da507f3ea8..9f318f1ad2 100644
--- a/apps/web/src/lib/graphql-cache/worker/browser-test/notification-projection-harness.ts
+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/notification-projection-harness.ts
@@ -6,6 +6,8 @@ const host = createWorkerCacheHost({
scope: `notification-projection-${crypto.randomUUID()}`,
requestTimeoutMs: 30_000,
});
+const channel = new URL(location.href).searchParams.get('entity') === 'channel';
+const entityType = channel ? 'CHANNEL' : 'PROJECT';
const projectId = '00000000-0000-0000-0000-000000000001';
const ids = [
'00000000-0000-0000-0000-000000000011',
@@ -17,6 +19,9 @@ const snapshotQuery = `query Snapshot {
__typename id cacheProjection
notifications { id entityId entityType state }
... on GraphqlSoupProject { ownerId parentId createdAt updatedAt }
+ ... on GraphqlSoupChannel {
+ ownerId channelType channelTeamId: teamId organizationId isParticipant createdAt updatedAt
+ }
} } }
}`;
const updateQuery = `mutation Update($input: UpdateNotificationsInput!) {
@@ -26,10 +31,10 @@ const notification = (id: string, state: string) => ({
__typename: 'GraphqlNotification',
id,
entityId: projectId,
- entityType: 'PROJECT',
+ entityType,
state,
});
-const unhydratedNotifications = ['DOCUMENT', 'PROJECT', 'CHAT'].map(
+const unhydratedNotifications = ['DOCUMENT', 'PROJECT', 'CHAT', 'CHANNEL'].map(
(entityType, index) => ({
...notification(`00000000-0000-0000-0000-00000000002${index}`, 'UNSEEN'),
entityType,
@@ -39,10 +44,14 @@ const unhydratedNotifications = ['DOCUMENT', 'PROJECT', 'CHAT'].map(
const filters = (state: string) => ({
calendarEventFilter: { literal: { id: nil } },
documentFilter: { literal: { id: nil } },
- projectFilter: { literal: { notificationState: state } },
+ projectFilter: {
+ literal: channel ? { projectIdSelf: nil } : { notificationState: state },
+ },
chatFilter: { literal: { chatId: nil } },
emailFilter: { tree: { literal: { threadId: nil } } },
- channelFilter: { literal: { channelId: nil } },
+ channelFilter: {
+ literal: channel ? { notificationState: state } : { channelId: nil },
+ },
channelThreadFilter: { literal: { threadId: nil } },
callFilter: { literal: { callId: nil } },
crmCompanyFilter: { literal: { id: nil } },
@@ -83,7 +92,11 @@ const snapshot = (
soup: {
items: [
{
- __typename: 'GraphqlSoupProject',
+ __typename: channel ? 'GraphqlSoupChannel' : 'GraphqlSoupProject',
+ channelType: 'team',
+ channelTeamId: '00000000-0000-0000-0000-000000000050',
+ organizationId: null,
+ isParticipant: true,
id: entityId,
cacheProjection: null,
ownerId: 'macro|[email protected]',
@@ -123,6 +136,35 @@ const markDone = (id: string) =>
try {
await seed();
await expectCount('Secondary edges preserve local filtering', 'UNSEEN', 1);
+ if (channel) {
+ for (const participation of [
+ { not: { literal: { isParticipant: false } } },
+ {
+ or: {
+ left: { literal: { isParticipant: true } },
+ right: { literal: { importance: false } },
+ },
+ },
+ ]) {
+ const input = filters('UNSEEN');
+ const result = await host.entityFilter({
+ filters: {
+ ...input,
+ channelFilter: {
+ and: { left: input.channelFilter, right: participation },
+ },
+ },
+ sortMethod: 'UPDATED_AT',
+ sortDirection: 'DESC',
+ limit: 20,
+ });
+ if (result.kind !== 'complete' || result.keys.length !== 1)
+ throw new Error(
+ `equivalent participation filter: ${JSON.stringify(result)}`
+ );
+ }
+ report.push('Equivalent participant filters: local');
+ }
for (const row of unhydratedNotifications) {
await host.writeQuery({
query: updateQuery,
diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/notification-projection.browser.e2e.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/notification-projection.browser.e2e.ts
index 2a37369098..19ad9644c1 100644
--- a/apps/web/src/lib/graphql-cache/worker/browser-test/notification-projection.browser.e2e.ts
+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/notification-projection.browser.e2e.ts
@@ -1,35 +1,42 @@
import { expect, test } from '@playwright/test';
-test('notification state memberships survive optimistic rollback and authoritative changes', async ({
- page,
-}) => {
- await page.goto('/notification-projection.html');
- await expect(page.locator('#result')).toHaveAttribute(
- 'data-status',
- 'passed',
- { timeout: 60_000 }
- );
- await expect(page.locator('#result')).toContainText(
- 'Secondary edges preserve local filtering: 1'
- );
- for (const kind of ['DOCUMENT', 'PROJECT', 'CHAT']) {
- for (const operation of ['inbox update', 'optimism', 'deletion']) {
+for (const entity of ['project', 'channel']) {
+ test(`${entity} notification state memberships survive optimistic rollback and authoritative changes`, async ({
+ page,
+ }) => {
+ await page.goto(`/notification-projection.html?entity=${entity}`);
+ await expect(page.locator('#result')).toHaveAttribute(
+ 'data-status',
+ 'passed',
+ { timeout: 60_000 }
+ );
+ await expect(page.locator('#result')).toContainText(
+ 'Secondary edges preserve local filtering: 1'
+ );
+ if (entity === 'channel') {
await expect(page.locator('#result')).toContainText(
- `Unhydrated ${kind} ${operation}: 1`
+ 'Equivalent participant filters: local'
);
}
- }
- await expect(page.locator('#result')).toContainText(
- 'Rollback restores only first notification: 1'
- );
- await expect(page.locator('#result')).toContainText('DONE: network-only');
- await expect(page.locator('#result')).toContainText(
- 'Write identity switch discards old associations: 1'
- );
- await expect(page.locator('#result')).toContainText(
- 'Hydration identity switch discards old associations: 1'
- );
- await expect(page.locator('#result')).toContainText(
- 'Identity-only notification cannot inherit a parent: 0'
- );
-});
+ for (const kind of ['DOCUMENT', 'PROJECT', 'CHAT', 'CHANNEL']) {
+ for (const operation of ['inbox update', 'optimism', 'deletion']) {
+ await expect(page.locator('#result')).toContainText(
+ `Unhydrated ${kind} ${operation}: 1`
+ );
+ }
+ }
+ await expect(page.locator('#result')).toContainText(
+ 'Rollback restores only first notification: 1'
+ );
+ await expect(page.locator('#result')).toContainText('DONE: network-only');
+ await expect(page.locator('#result')).toContainText(
+ 'Write identity switch discards old associations: 1'
+ );
+ await expect(page.locator('#result')).toContainText(
+ 'Hydration identity switch discards old associations: 1'
+ );
+ await expect(page.locator('#result')).toContainText(
+ 'Identity-only notification cannot inherit a parent: 0'
+ );
+ });
+}
diff --git a/apps/web/src/lib/queries/soup/backfill.test.tsx b/apps/web/src/lib/queries/soup/backfill.test.tsx
index 768a3b657e..7c508839fb 100644
--- a/apps/web/src/lib/queries/soup/backfill.test.tsx
+++ b/apps/web/src/lib/queries/soup/backfill.test.tsx
@@ -409,7 +409,7 @@ describe('runSoupBackfills', () => {
it('restarts from the beginning when the cache generation is replaced', async () => {
localStorage.setItem(
- 'graphql-soup-backfill:v11:user-1:core-entities',
+ 'graphql-soup-backfill:v12:user-1:core-entities',
JSON.stringify({
userId: 'user-1',
nextCursor: 'stale-cursor',
diff --git a/apps/web/src/lib/queries/soup/backfill.ts b/apps/web/src/lib/queries/soup/backfill.ts
index ab93d45437..5f0f488ecc 100644
--- a/apps/web/src/lib/queries/soup/backfill.ts
+++ b/apps/web/src/lib/queries/soup/backfill.ts
@@ -26,7 +26,8 @@ import { createEffect, createSignal, onCleanup } from 'solid-js';
// Bump when a default backfill input or completion guarantee changes so
// persisted cursors cannot retain an older hydration contract.
-const BACKFILL_VERSION = 11;
+// Rehydrate existing channel rows into the general Soup predicate profile.
+const BACKFILL_VERSION = 12;
const PAGE_LIMIT = 100;
// Five threads × twenty messages reaches the backend's 100-message cap.
const EMAIL_CONTENT_PAGE_LIMIT = 5;
diff --git a/crates/item_filter_index/src/channels.rs b/crates/item_filter_index/src/channels.rs
new file mode 100644
index 0000000000..e14899d41f
--- /dev/null
+++ b/crates/item_filter_index/src/channels.rs
@@ -0,0 +1,207 @@
+//! Channel predicates for the existing flat Soup projection profile.
+
+use super::*;
+
+fn mentions_participation(expr: &Expr<ChannelLiteral>) -> bool {
+ match expr {
+ Expr::Literal(ChannelLiteral::IsParticipant(_)) => true,
+ Expr::Literal(_) => false,
+ Expr::And(a, b) | Expr::Or(a, b) => mentions_participation(a) || mentions_participation(b),
+ Expr::Not(expr) => mentions_participation(expr),
+ }
+}
+
+/// Conservative evaluation with the viewer's participation fixed to false.
+/// Other facts are unknown; an omitted SQL clause is distinct from TRUE.
+#[derive(Clone, Copy)]
+enum NonParticipantMatch {
+ Omitted,
+ Always,
+ Never,
+ Possible,
+}
+
+fn non_participant_match(expr: &Expr<ChannelLiteral>) -> NonParticipantMatch {
+ use NonParticipantMatch::{Always, Never, Omitted, Possible};
+ match expr {
+ Expr::Literal(ChannelLiteral::IsParticipant(true) | ChannelLiteral::Importance(false)) => {
+ Never
+ }
+ Expr::Literal(ChannelLiteral::IsParticipant(false)) => Always,
+ Expr::Literal(ChannelLiteral::Importance(true)) => Omitted,
+ Expr::Literal(_) => Possible,
+ Expr::Not(expr) => match non_participant_match(expr) {
+ Always => Never,
+ Never => Always,
+ value @ (Omitted | Possible) => value,
+ },
+ Expr::And(a, b) | Expr::Or(a, b) => {
+ let (a, b) = (non_participant_match(a), non_participant_match(b));
+ // Match the server folder: omitted clauses disappear from both
+ // AND and OR, and stay omitted under NOT.
+ if let (Omitted, value) | (value, Omitted) = (a, b) {
+ return value;
+ }
+ if matches!(expr, Expr::And(..)) {
+ match (a, b) {
+ (Never, _) | (_, Never) => Never,
+ (Always, Always) => Always,
+ _ => Possible,
+ }
+ } else {
+ match (a, b) {
+ (Always, _) | (_, Always) => Always,
+ (Never, Never) => Never,
+ _ => Possible,
+ }
+ }
+ }
+ }
+}
+
+fn requires_participation(expr: &Expr<ChannelLiteral>) -> bool {
+ matches!(non_participant_match(expr), NonParticipantMatch::Never)
+}
+
+fn excluded(expr: Option<&Expr<ChannelLiteral>>) -> bool {
+ expr.is_some_and(|expr| {
+ proves_none(
+ expr,
+ |literal| matches!(literal, ChannelLiteral::ChannelId(id) if id.is_nil()),
+ )
+ })
+}
+
+pub(super) fn check(expr: Option<&Expr<ChannelLiteral>>) -> Result<(), UnsupportedReason> {
+ if excluded(expr) {
+ return Ok(());
+ }
+ if !supported_expr(expr, |literal| {
+ matches!(
+ literal,
+ ChannelLiteral::ChannelId(_)
+ | ChannelLiteral::OrganizationId(_)
+ | ChannelLiteral::TeamId(_)
+ | ChannelLiteral::ChannelType(_)
+ | ChannelLiteral::Importance(_)
+ | ChannelLiteral::IsParticipant(_)
+ ) || matches!(literal, ChannelLiteral::NotificationState(state) if active_notification_state(state))
+ }) {
+ return Err(UnsupportedReason::Literal("channel"));
+ }
+ // Mentioning participation widens the server candidate universe to team
+ // channels the viewer has not joined. Existing channel fields do not prove
+ // that independent team grant, so only participant-scoped requests qualify.
+ if expr.is_some_and(|expr| mentions_participation(expr) && !requires_participation(expr)) {
+ return Err(UnsupportedReason::Literal("channel-participation-scope"));
+ }
+ Ok(())
+}
+
+/// SQL predicates have separate true/false sets: NULL belongs to neither.
+/// Importance(true) is omitted by the server's channel AST folder, including
+/// inside OR/NOT; it is not a SQL TRUE literal.
+struct SqlPredicate {
+ positive: PredicateExpr,
+ negative: PredicateExpr,
+}
+
+fn fold(expr: &Expr<ChannelLiteral>) -> Result<Option<SqlPredicate>, CompileError> {
+ let boolean = |positive: PredicateExpr| SqlPredicate {
+ negative: PredicateExpr::Not(Box::new(positive.clone())),
+ positive,
+ };
+ Ok(Some(match expr {
+ Expr::Literal(ChannelLiteral::Importance(true)) => return Ok(None),
+ Expr::Literal(literal) => {
+ let (positive, nullable) = match literal {
+ ChannelLiteral::ChannelId(id) => (exact_uuid(vocabulary::id(), id), None),
+ ChannelLiteral::TeamId(id) => (
+ exact_uuid(vocabulary::channel_team(), id),
+ Some(vocabulary::channel_team()),
+ ),
+ ChannelLiteral::OrganizationId(id) => (
+ PredicateExpr::Exact {
+ attribute: vocabulary::channel_organization(),
+ value: ExactValue::new(id.to_be_bytes())?,
+ },
+ Some(vocabulary::channel_organization()),
+ ),
+ ChannelLiteral::ChannelType(kind) => (
+ exact_utf8(vocabulary::channel_type(), kind.to_string())?,
+ None,
+ ),
+ ChannelLiteral::IsParticipant(value) => (
+ PredicateExpr::Exact {
+ attribute: vocabulary::channel_participant(),
+ value: ExactValue::new([u8::from(*value)])?,
+ },
+ None,
+ ),
+ ChannelLiteral::Importance(false) => (PredicateExpr::None, None),
+ ChannelLiteral::NotificationState(state) => (notification_state_expr(state), None),
+ _ => unreachable!("channel eligibility checked"),
+ };
+ let mut result = boolean(positive);
+ if let Some(attribute) = nullable {
+ result.negative = PredicateExpr::And(
+ Box::new(PredicateExpr::ExactExists { attribute }),
+ Box::new(result.negative),
+ );
+ }
+ result
+ }
+ Expr::Not(expr) => {
+ let Some(value) = fold(expr)? else {
+ return Ok(None);
+ };
+ SqlPredicate {
+ positive: value.negative,
+ negative: value.positive,
+ }
+ }
+ Expr::And(a, b) | Expr::Or(a, b) => {
+ let (a, b) = match (fold(a)?, fold(b)?) {
+ (None, value) | (value, None) => return Ok(value),
+ (Some(a), Some(b)) => (a, b),
+ };
+ if matches!(expr, Expr::And(..)) {
+ SqlPredicate {
+ positive: PredicateExpr::And(Box::new(a.positive), Box::new(b.positive)),
+ negative: PredicateExpr::Or(Box::new(a.negative), Box::new(b.negative)),
+ }
+ } else {
+ SqlPredicate {
+ positive: PredicateExpr::Or(Box::new(a.positive), Box::new(b.positive)),
+ negative: PredicateExpr::And(Box::new(a.negative), Box::new(b.negative)),
+ }
+ }
+ }
+ }))
+}
+
+pub(super) fn compile(
+ expr: Option<&Expr<ChannelLiteral>>,
+) -> Result<PartitionPredicate, CompileError> {
+ if excluded(expr) {
+ return Ok(PartitionPredicate {
+ partition: vocabulary::channel_partition(),
+ predicate: PredicateExpr::None,
+ });
+ }
+ let predicate = expr
+ .map(fold)
+ .transpose()?
+ .flatten()
+ .map_or(PredicateExpr::All, |value| value.positive);
+ Ok(PartitionPredicate {
+ partition: vocabulary::channel_partition(),
+ predicate: PredicateExpr::And(
+ Box::new(predicate),
+ Box::new(PredicateExpr::Exact {
+ attribute: vocabulary::channel_participant(),
+ value: ExactValue::new([1])?,
+ }),
+ ),
+ })
+}
diff --git a/crates/item_filter_index/src/lib.rs b/crates/item_filter_index/src/lib.rs
index a49ee6bbeb..ab63d51d2b 100644
--- a/crates/item_filter_index/src/lib.rs
+++ b/crates/item_filter_index/src/lib.rs
@@ -26,6 +26,7 @@ use uuid::Uuid;
#[cfg(test)]
mod test;
+mod channels;
pub mod mail;
/// Stable direct-field profile name retained for existing browser projections.
@@ -97,6 +98,31 @@ pub mod vocabulary {
token("chat")
}
+ /// Channel partition in the browser-composed profile.
+ pub fn channel_partition() -> Token {
+ token("channel")
+ }
+
+ /// Canonical channel type.
+ pub fn channel_type() -> Token {
+ token("channel-type")
+ }
+
+ /// Channel team UUID, when present.
+ pub fn channel_team() -> Token {
+ token("channel-team")
+ }
+
+ /// Channel organization ID as a signed 64-bit big-endian integer.
+ pub fn channel_organization() -> Token {
+ token("channel-organization")
+ }
+
+ /// Whether the viewer is an active channel participant.
+ pub fn channel_participant() -> Token {
+ token("channel-participant")
+ }
+
/// Record identity attribute.
pub fn id() -> Token {
token("id")
@@ -268,6 +294,18 @@ fn check_soup_flat(
return Eligibility::Unsupported(UnsupportedReason::GlobalProperties);
}
+ if supports_notifications
+ && ast.properties_filter.is_some()
+ && unsupported_partition(
+ ast.channel_filter.as_deref(),
+ "channel",
+ |literal| matches!(literal, ChannelLiteral::ChannelId(id) if id.is_nil()),
+ )
+ .is_err()
+ {
+ return Eligibility::Unsupported(UnsupportedReason::GlobalProperties);
+ }
+
for result in [
unsupported_partition(
ast.calendar_event_filter.as_deref(),
@@ -284,11 +322,15 @@ fn check_soup_flat(
} else {
Ok(())
},
- unsupported_partition(
- ast.channel_filter.as_deref(),
- "channel",
- |literal| matches!(literal, ChannelLiteral::ChannelId(id) if id.is_nil()),
- ),
+ if supports_notifications {
+ channels::check(ast.channel_filter.as_deref())
+ } else {
+ unsupported_partition(
+ ast.channel_filter.as_deref(),
+ "channel",
+ |literal| matches!(literal, ChannelLiteral::ChannelId(id) if id.is_nil()),
+ )
+ },
unsupported_partition(
ast.channel_thread_filter.as_deref(),
"channelThread",
@@ -396,8 +438,9 @@ pub fn compile_soup_flat_v3(
)
}
-/// Compile exact UNSEEN/SEEN notification predicates in addition to v3 literals.
-/// DONE is intentionally unsupported: the active edge contains no done history.
+/// Compile participant-scoped Channels and exact UNSEEN/SEEN notification
+/// predicates in addition to v3 literals. DONE is intentionally unsupported:
+/// the active edge contains no done history.
pub fn compile_soup_flat_v4(
ast: &EntityFilterAst,
request: SoupFlatRequest,
@@ -510,6 +553,12 @@ fn compile_soup_flat(
limit: request.limit,
};
+ let mut query = query;
+ if supports_notifications {
+ query
+ .partitions
+ .push(channels::compile(ast.channel_filter.as_deref())?);
+ }
Ok(LocalCompileOutcome::Supported(ValidatedIndexQuery::new(
query,
)?))
diff --git a/crates/item_filter_index/src/test.rs b/crates/item_filter_index/src/test.rs
index cbf9481eb6..8cd7cbab76 100644
--- a/crates/item_filter_index/src/test.rs
+++ b/crates/item_filter_index/src/test.rs
@@ -20,6 +20,8 @@ use predicate_index::{PredicateExpr, RangeBound};
use super::*;
+mod channels;
+
fn request() -> SoupFlatRequest {
SoupFlatRequest {
sort: SoupIndexSort::UpdatedAt,
diff --git a/crates/item_filter_index/src/test/channels.rs b/crates/item_filter_index/src/test/channels.rs
new file mode 100644
index 0000000000..2f675984f3
--- /dev/null
+++ b/crates/item_filter_index/src/test/channels.rs
@@ -0,0 +1,198 @@
+use super::*;
+use item_filters::{NotificationState, ast::channel::ChannelTypeFilter};
+use predicate_index::{ExactFact, IndexDocument, RecordKey};
+
+fn channel(participant: bool, team: Option<u128>, org: Option<i64>) -> IndexDocument {
+ let mut facts = vec![
+ ExactFact {
+ attribute: vocabulary::id(),
+ value: ExactValue::new(Uuid::from_u128(1).as_bytes()).unwrap(),
+ },
+ ExactFact {
+ attribute: vocabulary::channel_type(),
+ value: ExactValue::utf8("team").unwrap(),
+ },
+ ExactFact {
+ attribute: vocabulary::channel_participant(),
+ value: ExactValue::new([u8::from(participant)]).unwrap(),
+ },
+ ];
+ if let Some(team) = team {
+ facts.push(ExactFact {
+ attribute: vocabulary::channel_team(),
+ value: ExactValue::new(Uuid::from_u128(team).as_bytes()).unwrap(),
+ });
+ }
+ if let Some(org) = org {
+ facts.push(ExactFact {
+ attribute: vocabulary::channel_organization(),
+ value: ExactValue::new(org.to_be_bytes()).unwrap(),
+ });
+ }
+ IndexDocument {
+ record_key: RecordKey::new("GraphqlSoupChannel:1").unwrap(),
+ profile: vocabulary::profile_v4(),
+ partition: vocabulary::channel_partition(),
+ exact_facts: facts,
+ integer_facts: vec![],
+ sort_facts: vec![],
+ }
+}
+
+fn predicate(expr: Option<Expr<ChannelLiteral>>) -> PredicateExpr {
+ let mut ast = excluded_deferred_partitions();
+ ast.channel_filter = expr.map(Arc::new);
+ let LocalCompileOutcome::Supported(query) = compile_soup_flat_v4(&ast, request()).unwrap()
+ else {
+ panic!("supported channel filter")
+ };
+ query
+ .as_query()
+ .partitions
+ .iter()
+ .find(|p| p.partition == vocabulary::channel_partition())
+ .unwrap()
+ .predicate
+ .clone()
+}
+
+#[test]
+fn general_soup_supports_channels_without_enabling_legacy_profiles() {
+ let mut ast = excluded_deferred_partitions();
+ ast.channel_filter = None;
+ assert!(matches!(
+ compile_soup_flat_v3(&ast, request()).unwrap(),
+ LocalCompileOutcome::Unsupported(UnsupportedReason::Partition("channel"))
+ ));
+ assert!(channel(true, None, None).matches(&predicate(None)));
+ assert!(!channel(false, None, None).matches(&predicate(None)));
+ let active = predicate(Some(Expr::val(ChannelLiteral::NotificationState(
+ NotificationState::Unseen,
+ ))));
+ let mut doc = channel(true, None, None);
+ assert!(!doc.matches(&active));
+ doc.exact_facts.push(ExactFact {
+ attribute: vocabulary::notification_unseen(),
+ value: ExactValue::new(Uuid::from_u128(2).as_bytes()).unwrap(),
+ });
+ assert!(doc.matches(&active));
+}
+
+#[test]
+fn channel_nullable_filters_preserve_sql_three_valued_logic() {
+ let team = Expr::val(ChannelLiteral::TeamId(Uuid::from_u128(10)));
+ let org = Expr::val(ChannelLiteral::OrganizationId(20));
+ let cases = [
+ (Expr::is_not(team.clone()), [false, false, true]),
+ (
+ Expr::is_not(Expr::or(team.clone(), org.clone())),
+ [false, false, true],
+ ),
+ (Expr::is_not(Expr::and(team, org)), [false, false, true]),
+ ];
+ let docs = [
+ channel(true, None, None),
+ channel(true, Some(10), Some(20)),
+ channel(true, Some(11), Some(21)),
+ ];
+ for (expr, expected) in cases {
+ let predicate = predicate(Some(expr));
+ for (document, expected) in docs.iter().zip(expected) {
+ assert_eq!(document.matches(&predicate), expected);
+ }
+ }
+}
+
+#[test]
+fn channel_importance_true_matches_the_servers_omitted_clause() {
+ let importance = Expr::val(ChannelLiteral::Importance(true));
+ let dm = Expr::val(ChannelLiteral::ChannelType(
+ ChannelTypeFilter::DirectMessage,
+ ));
+ assert!(!channel(true, None, None).matches(&predicate(Some(Expr::or(importance.clone(), dm)))));
+ assert!(channel(true, None, None).matches(&predicate(Some(Expr::is_not(importance)))));
+ assert!(
+ !channel(true, None, None).matches(&predicate(Some(Expr::val(
+ ChannelLiteral::Importance(false)
+ ))))
+ );
+}
+
+#[test]
+fn equivalent_participant_scopes_compile_locally() {
+ let member = Expr::val(ChannelLiteral::IsParticipant(true));
+ let nonmember = Expr::val(ChannelLiteral::IsParticipant(false));
+ let omitted = Expr::val(ChannelLiteral::Importance(true));
+ let never = Expr::val(ChannelLiteral::Importance(false));
+ for expr in [
+ Expr::is_not(nonmember.clone()),
+ Expr::or(member.clone(), never.clone()),
+ Expr::or(never.clone(), member.clone()),
+ Expr::is_not(Expr::is_not(member.clone())),
+ Expr::is_not(Expr::and(nonmember.clone(), omitted.clone())),
+ Expr::is_not(Expr::or(nonmember, omitted.clone())),
+ Expr::or(member.clone(), omitted),
+ Expr::is_not(Expr::and(Expr::is_not(member), Expr::is_not(never))),
+ ] {
+ let predicate = predicate(Some(expr));
+ assert!(channel(true, None, None).matches(&predicate));
+ assert!(!channel(false, None, None).matches(&predicate));
+ }
+}
+
+#[test]
+fn participation_scope_constant_folding_never_widens_access() {
+ let member = Expr::val(ChannelLiteral::IsParticipant(true));
+ let nonmember = Expr::val(ChannelLiteral::IsParticipant(false));
+ let omitted = Expr::val(ChannelLiteral::Importance(true));
+ let never = Expr::val(ChannelLiteral::Importance(false));
+ for expr in [
+ Expr::is_not(Expr::and(member.clone(), omitted)),
+ Expr::or(member, Expr::is_not(never.clone())),
+ Expr::is_not(Expr::and(nonmember.clone(), never.clone())),
+ Expr::is_not(Expr::is_not(nonmember.clone())),
+ Expr::is_not(Expr::and(
+ nonmember.clone(),
+ Expr::val(ChannelLiteral::TeamId(Uuid::from_u128(10))),
+ )),
+ ] {
+ let mut ast = excluded_deferred_partitions();
+ ast.channel_filter = Some(Arc::new(expr));
+ assert!(matches!(
+ compile_soup_flat_v4(&ast, request()).unwrap(),
+ LocalCompileOutcome::Unsupported(UnsupportedReason::Literal(
+ "channel-participation-scope"
+ ))
+ ));
+ }
+ let empty = predicate(Some(Expr::and(nonmember, never)));
+ assert!(!channel(true, None, None).matches(&empty));
+ assert!(!channel(false, None, None).matches(&empty));
+}
+
+#[test]
+fn deferred_channel_predicates_and_widened_access_stay_network_only() {
+ for expr in [
+ Expr::val(ChannelLiteral::ThreadId(Uuid::from_u128(1))),
+ Expr::val(ChannelLiteral::NotificationState(NotificationState::Done)),
+ Expr::val(ChannelLiteral::IsParticipant(false)),
+ Expr::is_not(Expr::val(ChannelLiteral::IsParticipant(true))),
+ Expr::or(
+ Expr::val(ChannelLiteral::IsParticipant(true)),
+ Expr::val(ChannelLiteral::ChannelType(ChannelTypeFilter::Team)),
+ ),
+ ] {
+ let mut ast = excluded_deferred_partitions();
+ ast.channel_filter = Some(Arc::new(expr));
+ assert!(matches!(
+ compile_soup_flat_v4(&ast, request()).unwrap(),
+ LocalCompileOutcome::Unsupported(_)
+ ));
+ }
+ let member = predicate(Some(Expr::and(
+ Expr::val(ChannelLiteral::Importance(true)),
+ Expr::val(ChannelLiteral::IsParticipant(true)),
+ )));
+ assert!(channel(true, None, None).matches(&member));
+ assert!(!channel(false, None, None).matches(&member));
+}
diff --git a/crates/soup_filter_cache_adapter/src/channels.rs b/crates/soup_filter_cache_adapter/src/channels.rs
new file mode 100644
index 0000000000..58f7ade33f
--- /dev/null
+++ b/crates/soup_filter_cache_adapter/src/channels.rs
@@ -0,0 +1,158 @@
+//! Channel metadata in the existing Soup snapshot, patch, and notification paths.
+
+use super::*;
+use predicate_index::{IntegerAttributePatch, IntegerFact, utc_timestamp_micros};
+use soup_filter_projection::channel::{ChannelProjectionInput, project_channel};
+
+type Object = serde_json::Map<String, serde_json::Value>;
+
+pub(super) fn selected_object(object: &Object, fields: &[&FieldNode]) -> Result<Object, ()> {
+ let mut selected = Object::new();
+ for field in fields {
+ let Some(value) = object.get(&field.response_key) else {
+ continue;
+ };
+ if selected.get(&field.name).is_some_and(|old| old != value) {
+ return Err(());
+ }
+ selected.insert(field.name.clone(), value.clone());
+ }
+ Ok(selected)
+}
+
+fn organization(value: &serde_json::Value) -> Result<Option<i64>, ()> {
+ if value.is_null() {
+ return Ok(None);
+ }
+ Ok(Some(
+ value.as_str().ok_or(())?.parse::<i64>().map_err(|_| ())?,
+ ))
+}
+
+fn channel_type(value: &serde_json::Value) -> Result<&str, ()> {
+ match value.as_str() {
+ Some(kind @ ("public" | "private" | "team" | "direct_message")) => Ok(kind),
+ _ => Err(()),
+ }
+}
+
+pub(super) fn complete(record_key: RecordKey, object: &Object) -> Result<IndexDocument, ()> {
+ if object.get("cacheProjection") != Some(&serde_json::Value::Null) {
+ return Err(());
+ }
+ let input = ChannelProjectionInput {
+ record_key,
+ id: uuid::Uuid::parse_str(
+ object
+ .get("id")
+ .and_then(serde_json::Value::as_str)
+ .ok_or(())?,
+ )
+ .map_err(|_| ())?,
+ owner: object
+ .get("ownerId")
+ .and_then(serde_json::Value::as_str)
+ .ok_or(())?
+ .to_owned(),
+ channel_type: channel_type(object.get("channelType").ok_or(())?)?.to_owned(),
+ team_id: optional_uuid(object.get("teamId").ok_or(())?).ok_or(())?,
+ organization_id: organization(object.get("organizationId").ok_or(())?)?,
+ is_participant: object
+ .get("isParticipant")
+ .and_then(serde_json::Value::as_bool)
+ .ok_or(())?,
+ created_at: graphql_timestamp(object.get("createdAt").ok_or(())?).ok_or(())?,
+ updated_at: graphql_timestamp(object.get("updatedAt").ok_or(())?).ok_or(())?,
+ };
+ let document = project_channel(input).map_err(|_| ())?;
+ notifications::compose_active_notifications(document, object)
+}
+
+pub(super) fn patch(
+ record_key: RecordKey,
+ object: &Object,
+ updated_at_fallback_ms: Option<i64>,
+) -> Result<OptimisticProjectionMutation, ()> {
+ let mut exact = Vec::new();
+ if let Some(value) = object.get("ownerId") {
+ let owner = value.as_str().filter(|owner| !owner.is_empty()).ok_or(())?;
+ exact.push(ExactAttributePatch {
+ attribute: vocabulary::owner(),
+ values: vec![ExactValue::utf8(owner).map_err(|_| ())?],
+ });
+ }
+ if let Some(value) = object.get("channelType") {
+ exact.push(ExactAttributePatch {
+ attribute: vocabulary::channel_type(),
+ values: vec![ExactValue::utf8(channel_type(value)?).map_err(|_| ())?],
+ });
+ }
+ if let Some(value) = object.get("isParticipant") {
+ exact.push(ExactAttributePatch {
+ attribute: vocabulary::channel_participant(),
+ values: vec![ExactValue::new([u8::from(value.as_bool().ok_or(())?)]).map_err(|_| ())?],
+ });
+ }
+ // Optimistic payloads use the alias from the generated Soup fragment; the
+ // selected authoritative path has already resolved arbitrary aliases.
+ if let Some(value) = object.get("teamId").or_else(|| object.get("channelTeamId")) {
+ exact.push(ExactAttributePatch {
+ attribute: vocabulary::channel_team(),
+ values: optional_uuid(value)
+ .ok_or(())?
+ .map(|id| ExactValue::new(id.as_bytes()))
+ .transpose()
+ .map_err(|_| ())?
+ .into_iter()
+ .collect(),
+ });
+ }
+ if let Some(value) = object.get("organizationId") {
+ exact.push(ExactAttributePatch {
+ attribute: vocabulary::channel_organization(),
+ values: organization(value)?
+ .map(|id| ExactValue::new(id.to_be_bytes()))
+ .transpose()
+ .map_err(|_| ())?
+ .into_iter()
+ .collect(),
+ });
+ }
+ if object.contains_key("notifications") {
+ exact.extend(notifications::snapshot_patches(&record_key, object)?);
+ }
+ let mut integers = Vec::new();
+ let mut sorts = Vec::new();
+ for (field, attribute) in [
+ ("createdAt", vocabulary::created_at()),
+ ("updatedAt", vocabulary::updated_at()),
+ ] {
+ let timestamp = match object.get(field) {
+ Some(value) => Some(graphql_timestamp(value).ok_or(())?),
+ None if field == "updatedAt" => match updated_at_fallback_ms {
+ Some(ms) => Some(chrono::DateTime::from_timestamp_millis(ms).ok_or(())?),
+ None => None,
+ },
+ None => None,
+ };
+ if let Some(timestamp) = timestamp {
+ let value = utc_timestamp_micros(timestamp);
+ integers.push(IntegerAttributePatch {
+ attribute: attribute.clone(),
+ values: vec![value],
+ });
+ sorts.push(IntegerFact { attribute, value });
+ }
+ }
+ Ok(OptimisticProjectionMutation::Patch {
+ record_key,
+ profile: vocabulary::profile_v4(),
+ partition: vocabulary::channel_partition(),
+ exact,
+ integers,
+ sorts,
+ })
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/soup_filter_cache_adapter/src/channels/test.rs b/crates/soup_filter_cache_adapter/src/channels/test.rs
new file mode 100644
index 0000000000..130a449b4a
--- /dev/null
+++ b/crates/soup_filter_cache_adapter/src/channels/test.rs
@@ -0,0 +1,410 @@
+use super::*;
+use cache_core::{
+ engine::{BeginOptimisticWrite, Engine, NetworkWrite},
+ predicate::{PredicateIndexStorage, ProjectionState},
+ queue::{MutationClaimRequest, MutationClaimToken},
+ store::InMemoryStorage,
+};
+use serde_json::{Value, json};
+
+const QUERY: &str = r#"query ChannelSeed { user { id soup(input: {initial: {}}) { items {
+ __typename id cacheProjection notifications { id entityId entityType state }
+ ... on GraphqlSoupChannel {
+ ownerId channelType channelTeamId: teamId organizationId isParticipant createdAt updatedAt
+ }
+ ... on GraphqlSoupProject { ownerId parentId createdAt updatedAt }
+} } } }"#;
+const PATCH: &str = r#"query ChannelPatch { user { id soup(input: {initial: {}}) { items {
+ __typename id ... on GraphqlSoupChannel { channelTeamId: teamId isParticipant updatedAt }
+} } } }"#;
+const NOTIFICATION: &str =
+ r#"mutation Done { updateNotifications(input: {notificationIds: []}) { id state } }"#;
+
+fn id(n: u128) -> String {
+ uuid::Uuid::from_u128(n).to_string()
+}
+fn key(n: u128) -> RecordKey {
+ RecordKey::new(format!("GraphqlSoupChannel:{}", id(n))).unwrap()
+}
+fn row(n: u128) -> Value {
+ json!({"__typename":"GraphqlSoupChannel", "id":id(n), "cacheProjection":null,
+ "ownerId":"macro|[email protected]", "channelType":"team", "channelTeamId":id(10),
+ "organizationId":"20", "isParticipant":n != 3, "createdAt":"2025-01-01T00:00:00Z", "updatedAt":"2025-01-02T00:00:00.000001Z",
+ "notifications":[{"id":id(n+100),"entityId":id(n),"entityType":"CHANNEL","state":"UNSEEN"}]
+ })
+}
+fn data(rows: Vec<Value>) -> Value {
+ json!({"user":{"id":"macro|[email protected]","soup":{"items":rows}}})
+}
+fn filters(channel: Value) -> Value {
+ let nil = id(0);
+ json!({"documentFilter":{"literal":{"id":nil}},"projectFilter":{"literal":{"projectIdSelf":nil}},"chatFilter":{"literal":{"chatId":nil}},"calendarEventFilter":{"literal":{"id":nil}},"emailFilter":{"tree":{"literal":{"threadId":nil}}},"channelThreadFilter":{"literal":{"threadId":nil}},"callFilter":{"literal":{"callId":nil}},"crmCompanyFilter":{"literal":{"id":nil}},"foreignEntityFilter":{"literal":{"id":nil}},"channelFilter":channel})
+}
+async fn write<S: PredicateIndexStorage>(engine: &mut Engine<S>, query: &str, data: &Value) {
+ let projections = authoritative_projection_mutations(query, None, data).unwrap();
+ engine
+ .write_query_with_registration_and_projections(
+ None,
+ None,
+ NetworkWrite {
+ query,
+ operation_name: None,
+ variables: &Default::default(),
+ data,
+ identity: Some("macro|[email protected]"),
+ },
+ projections,
+ )
+ .await
+ .unwrap();
+}
+async fn keys<S: PredicateIndexStorage>(engine: &mut Engine<S>, filter: Value) -> Vec<RecordKey> {
+ let SoupFilterCompileOutcome::Supported(query) =
+ compile_filter_request(filters(filter), "UPDATED_AT", "DESC", 20).unwrap()
+ else {
+ panic!("supported")
+ };
+ engine
+ .reconcile_predicate_index(&query, &[])
+ .await
+ .unwrap()
+ .value
+ .keys
+}
+
+#[test]
+fn canonical_channel_fields_and_aliased_team_id_form_v4_snapshots() {
+ let projections = authoritative_projection_mutations(QUERY, None, &data(vec![row(1)])).unwrap();
+ let [ProjectionMutation::Replace(document)] = projections.as_slice() else {
+ panic!("complete channel")
+ };
+ soup_filter_projection::validate_soup_flat_v4(document).unwrap();
+ assert_eq!(document.partition, vocabulary::channel_partition());
+ assert!(
+ document
+ .exact_facts
+ .iter()
+ .any(|fact| fact.attribute == vocabulary::channel_team()
+ && fact.value.as_bytes() == uuid::Uuid::from_u128(10).as_bytes())
+ );
+ assert!(
+ document
+ .exact_facts
+ .iter()
+ .any(|fact| fact.attribute == vocabulary::notification_unseen())
+ );
+ let mut malformed = document.clone();
+ malformed
+ .exact_facts
+ .retain(|fact| fact.attribute != vocabulary::channel_participant());
+ assert!(soup_filter_projection::validate_soup_flat_v4(&malformed).is_err());
+ assert!(soup_filter_projection::validate_soup_flat_v3(document).is_err());
+}
+
+#[test]
+fn channel_aliases_preserve_identity_and_reject_conflicting_nullable_facts() {
+ let query = QUERY.replace(
+ "__typename id cacheProjection",
+ "__typename identity: id capsule: cacheProjection",
+ );
+ let mut aliased = row(1);
+ aliased["identity"] = aliased["id"].take();
+ aliased.as_object_mut().unwrap().remove("id");
+ aliased["capsule"] = aliased["cacheProjection"].take();
+ aliased.as_object_mut().unwrap().remove("cacheProjection");
+ assert!(
+ matches!(authoritative_projection_mutations(&query, None, &data(vec![aliased])).unwrap().as_slice(), [ProjectionMutation::Replace(document)] if document.record_key == key(1))
+ );
+
+ let duplicate = QUERY.replace(
+ "channelTeamId: teamId",
+ "channelTeamId: teamId otherTeam: teamId",
+ );
+ let mut conflict = row(1);
+ conflict["otherTeam"] = json!(id(11));
+ assert!(matches!(
+ authoritative_projection_mutations(&duplicate, None, &data(vec![conflict]))
+ .unwrap()
+ .as_slice(),
+ [ProjectionMutation::MarkIncomplete { .. }]
+ ));
+}
+
+#[test]
+fn organization_ids_preserve_the_signed_64_bit_projection_domain() {
+ for organization_id in [
+ i64::MIN,
+ -1,
+ 0,
+ i64::from(u32::MAX),
+ i64::from(u32::MAX) + 1,
+ i64::MAX,
+ ] {
+ let value = json!(organization_id.to_string());
+ assert_eq!(organization(&value), Ok(Some(organization_id)));
+ let mut channel = row(1);
+ channel["organizationId"] = value.clone();
+ let updates =
+ authoritative_projection_mutations(QUERY, None, &data(vec![channel])).unwrap();
+ let [ProjectionMutation::Replace(document)] = updates.as_slice() else {
+ panic!("complete i64 organization snapshot: {organization_id}")
+ };
+ let SoupFilterCompileOutcome::Supported(query) = compile_filter_request(
+ filters(json!({"literal":{"organizationId":organization_id}})),
+ "UPDATED_AT",
+ "DESC",
+ 20,
+ )
+ .unwrap() else {
+ panic!("organization filter")
+ };
+ let predicate = &query
+ .as_query()
+ .partitions
+ .iter()
+ .find(|part| part.partition == vocabulary::channel_partition())
+ .unwrap()
+ .predicate;
+ assert!(document.matches(predicate));
+ let update = patch(
+ key(1),
+ json!({"organizationId":value}).as_object().unwrap(),
+ None,
+ )
+ .unwrap();
+ let OptimisticProjectionMutation::Patch { exact, .. } = update else {
+ panic!("organization patch")
+ };
+ assert_eq!(exact.len(), 1);
+ assert_eq!(exact[0].attribute, vocabulary::channel_organization());
+ assert_eq!(exact[0].values[0].as_bytes(), organization_id.to_be_bytes());
+ }
+ assert_eq!(organization(&Value::Null), Ok(None));
+ for invalid in [
+ json!("9223372036854775808"),
+ json!("-9223372036854775809"),
+ json!("invalid"),
+ json!(1),
+ json!("1.5"),
+ ] {
+ assert!(organization(&invalid).is_err());
+ }
+}
+
+#[test]
+fn partial_and_invalid_channel_snapshots_do_not_invent_completeness() {
+ for field in [
+ "notifications",
+ "channelType",
+ "isParticipant",
+ "channelTeamId",
+ "organizationId",
+ "ownerId",
+ "updatedAt",
+ ] {
+ let mut incomplete = row(1);
+ incomplete.as_object_mut().unwrap().remove(field);
+ assert!(
+ matches!(
+ authoritative_projection_mutations(QUERY, None, &data(vec![incomplete]))
+ .unwrap()
+ .as_slice(),
+ [ProjectionMutation::MarkIncomplete { .. }]
+ ),
+ "{field}"
+ );
+ }
+ for (field, invalid) in [
+ ("channelType", json!("unknown")),
+ ("isParticipant", Value::Null),
+ ("organizationId", json!("invalid")),
+ ("cacheProjection", json!("unexpected")),
+ ] {
+ let mut malformed = row(1);
+ malformed[field] = invalid;
+ assert!(matches!(
+ authoritative_projection_mutations(QUERY, None, &data(vec![malformed]))
+ .unwrap()
+ .as_slice(),
+ [ProjectionMutation::MarkIncomplete { .. }]
+ ));
+ }
+ let mut nullable = row(1);
+ nullable["channelTeamId"] = Value::Null;
+ nullable["organizationId"] = Value::Null;
+ assert!(matches!(
+ authoritative_projection_mutations(QUERY, None, &data(vec![nullable]))
+ .unwrap()
+ .as_slice(),
+ [ProjectionMutation::Replace(_)]
+ ));
+}
+
+#[test]
+fn full_channel_optimism_does_not_create_authoritative_access() {
+ use cache_core::predicate::{ProjectionMutationLayer, compose_effective_optimistic_projection};
+ let mutations = optimistic_projection_mutations(&data(vec![row(1)]), 1);
+ assert!(matches!(
+ mutations.as_slice(),
+ [OptimisticProjectionMutation::Patch { .. }]
+ ));
+ let shadow = compose_effective_optimistic_projection(
+ &key(1),
+ None,
+ &[ProjectionMutationLayer {
+ owner: 1,
+ mutations: &mutations,
+ }],
+ )
+ .unwrap()
+ .unwrap();
+ assert!(matches!(
+ shadow.state,
+ predicate_index::OptimisticProjectionState::Incomplete { .. }
+ ));
+}
+
+async fn lifecycle<S: PredicateIndexStorage>(storage: S) {
+ let mut engine = Engine::new(storage);
+ let project = json!({"__typename":"GraphqlSoupProject","id":id(7),"cacheProjection":null,
+ "ownerId":"macro|[email protected]","parentId":null,"createdAt":"2025-01-01T00:00:00Z","updatedAt":"2025-01-02T00:00:00.000001Z",
+ "notifications":[{"id":id(107),"entityId":id(7),"entityType":"PROJECT","state":"UNSEEN"}]
+ });
+ write(
+ &mut engine,
+ QUERY,
+ &data(vec![row(1), row(2), row(3), project]),
+ )
+ .await;
+ let mut mixed = filters(json!({"literal":{"notificationState":"UNSEEN"}}));
+ mixed["projectFilter"] = json!({"literal":{"notificationState":"UNSEEN"}});
+ let SoupFilterCompileOutcome::Supported(query) =
+ compile_filter_request(mixed, "UPDATED_AT", "DESC", 20).unwrap()
+ else {
+ panic!("mixed Soup filter")
+ };
+ let found = engine
+ .reconcile_predicate_index(&query, &[])
+ .await
+ .unwrap()
+ .value
+ .keys;
+ assert_eq!(
+ found,
+ [
+ RecordKey::new(format!("GraphqlSoupProject:{}", id(7))).unwrap(),
+ key(2),
+ key(1)
+ ]
+ );
+ let unseen = json!({"literal":{"notificationState":"UNSEEN"}});
+ assert_eq!(keys(&mut engine, unseen.clone()).await, [key(2), key(1)]);
+ let patch = data(vec![
+ json!({"__typename":"GraphqlSoupChannel","id":id(1),"isParticipant":false,"channelTeamId":null}),
+ ]);
+ let (transaction, _) = engine
+ .begin_optimistic_write_with_projections(
+ None,
+ BeginOptimisticWrite {
+ uuid: "00000000-0000-0000-0000-000000002000",
+ query: PATCH,
+ operation_name: None,
+ variables: &Default::default(),
+ data: &patch,
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 1,
+ },
+ optimistic_projection_mutations(&patch, 1),
+ )
+ .await
+ .unwrap();
+ engine = Engine::new(engine.into_storage());
+ assert_eq!(keys(&mut engine, unseen.clone()).await, [key(2)]);
+ let claim = engine
+ .claim_next_mutation(MutationClaimRequest {
+ owner: "test".into(),
+ now_ms: 1,
+ lease_expires_at_ms: 100,
+ })
+ .await
+ .unwrap()
+ .unwrap();
+ engine
+ .rollback_optimistic_write(
+ transaction,
+ MutationClaimToken {
+ owner: "test".into(),
+ generation: claim.lease_generation,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(keys(&mut engine, unseen.clone()).await, [key(2), key(1)]);
+
+ // A child notification update edits only its primary channel's membership.
+ let notification = json!({"updateNotifications":[{"id":id(101),"state":"DONE"}]});
+ let updates = notification_projection_updates(
+ engine.storage(),
+ NOTIFICATION,
+ None,
+ &Default::default(),
+ &notification,
+ )
+ .await
+ .unwrap();
+ assert!(
+ matches!(updates.as_slice(), [ProjectionMutation::PatchExact { record_key, .. }] if record_key == &key(1))
+ );
+ engine
+ .write_query_with_registration_and_projections(
+ None,
+ None,
+ NetworkWrite {
+ query: NOTIFICATION,
+ operation_name: None,
+ variables: &Default::default(),
+ data: &notification,
+ identity: Some("macro|[email protected]"),
+ },
+ updates,
+ )
+ .await
+ .unwrap();
+ assert_eq!(keys(&mut engine, unseen).await, [key(2)]);
+
+ // Partial metadata refresh clears optional facts, preserving notification
+ // state and completeness only when a canonical base exists.
+ write(&mut engine, PATCH, &patch).await;
+ assert_eq!(
+ keys(&mut engine, json!({"literal":{"teamId":id(10)}})).await,
+ [key(2)]
+ );
+ let partial = data(vec![
+ json!({"__typename":"GraphqlSoupChannel","id":id(4),"isParticipant":true}),
+ ]);
+ write(&mut engine, PATCH, &partial).await;
+ assert!(matches!(
+ engine
+ .storage()
+ .load_projection_states(&[key(4)])
+ .await
+ .unwrap()[0],
+ Some(ProjectionState::Incomplete { .. })
+ ));
+ let dirty = dirty_projection_mutations(&[key(2).as_str().to_owned()]);
+ assert!(
+ matches!(dirty.as_slice(), [ProjectionMutation::MarkIncomplete { partition, .. }] if partition == &vocabulary::channel_partition())
+ );
+}
+
+#[test]
+fn channel_lifecycle_in_memory() {
+ pollster::block_on(lifecycle(InMemoryStorage::new()));
+}
+#[test]
+fn channel_lifecycle_in_turso() {
+ pollster::block_on(lifecycle(
+ cache_turso::TursoStorage::open_in_memory("soup-channels").unwrap(),
+ ));
+}
diff --git a/crates/soup_filter_cache_adapter/src/lib.rs b/crates/soup_filter_cache_adapter/src/lib.rs
index 4658c7f9b5..253c0fa534 100644
--- a/crates/soup_filter_cache_adapter/src/lib.rs
+++ b/crates/soup_filter_cache_adapter/src/lib.rs
@@ -23,6 +23,7 @@ use soup_filter_projection::{
};
use std::collections::HashSet;
+mod channels;
pub mod mail;
mod notifications;
pub use notifications::{
@@ -177,7 +178,17 @@ fn walk_authoritative_object(
collect_applicable_fields(selections, concrete_type, &mut fields);
if let Some(partition) = projection_partition(concrete_type) {
- let mut projection_object = object.clone();
+ let (mut projection_object, valid_selection) =
+ if partition == vocabulary::channel_partition() {
+ match channels::selected_object(object, &fields) {
+ Ok(selected) => (selected, true),
+ // Use the original ID only to invalidate a conflicting snapshot;
+ // never interpret conflicting nullable aliases as absent facts.
+ Err(()) => (object.clone(), false),
+ }
+ } else {
+ (object.clone(), true)
+ };
projection_object.remove("notifications");
if let Some(snapshot) = notifications::selected_snapshot(object, &fields) {
projection_object.insert("notifications".into(), snapshot);
@@ -190,7 +201,7 @@ fn walk_authoritative_object(
projection_fields.sort_by(|left, right| left.response_key.cmp(&right.response_key));
projection_fields.dedup_by(|left, right| left.response_key == right.response_key);
- let normalized_key = object
+ let normalized_key = projection_object
.get("id")
.and_then(serde_json::Value::as_str)
.map(|id| format!("{concrete_type}:{id}"))
@@ -200,8 +211,14 @@ fn walk_authoritative_object(
.map(|key| (key_text, key))
});
if let Some((key_text, record_key)) = normalized_key {
- let kind = projection_kind(&partition).expect("supported partition has a kind");
- let mutation = if projection_fields.is_empty() {
+ let mutation = if !valid_selection {
+ Some(ProjectionMutation::MarkIncomplete {
+ record_key,
+ profile: vocabulary::profile_v4(),
+ partition,
+ kind: ProjectionIncompleteKind::Dirty,
+ })
+ } else if projection_fields.is_empty() {
match authoritative_v4_patch_for_object(
record_key.clone(),
partition.clone(),
@@ -215,7 +232,7 @@ fn walk_authoritative_object(
kind: ProjectionIncompleteKind::Dirty,
}),
}
- } else if kind == SoupFlatEntityKind::Document {
+ } else if partition == vocabulary::document_partition() {
Some(selected_document_projection_for_object(
record_key,
partition,
@@ -546,6 +563,9 @@ fn complete_v4_projection_for_object(
object: &serde_json::Map<String, serde_json::Value>,
supplement: Option<&SoupCacheProjectionSupplement>,
) -> Result<IndexDocument, ()> {
+ if partition == vocabulary::channel_partition() {
+ return channels::complete(record_key, object);
+ }
let input =
direct_projection_input_for_object(record_key, &partition, object, None).ok_or(())?;
let sub_type = if input.kind == SoupFlatEntityKind::Document {
@@ -562,6 +582,27 @@ fn authoritative_v4_patch_for_object(
partition: Token,
object: &serde_json::Map<String, serde_json::Value>,
) -> Result<ProjectionMutation, ()> {
+ if partition == vocabulary::channel_partition() {
+ let OptimisticProjectionMutation::Patch {
+ record_key,
+ profile,
+ partition,
+ exact,
+ integers,
+ sorts,
+ } = channels::patch(record_key, object, None)?
+ else {
+ return Err(());
+ };
+ return Ok(ProjectionMutation::Patch {
+ record_key,
+ profile,
+ partition,
+ exact,
+ integers,
+ sorts,
+ });
+ }
let kind = projection_kind(&partition).ok_or(())?;
let project_field = if kind == SoupFlatEntityKind::Project {
"parentId"
@@ -673,6 +714,11 @@ fn optimistic_projection_for_object(
object: &serde_json::Map<String, serde_json::Value>,
created_at_ms: i64,
) -> Option<OptimisticProjectionMutation> {
+ if partition == vocabulary::channel_partition() {
+ // Cached channel access is authoritative. Optimism may patch a known
+ // base but cannot fabricate a complete, newly accessible channel.
+ return channels::patch(record_key, object, Some(created_at_ms)).ok();
+ }
let kind = projection_kind(&partition)?;
if kind != SoupFlatEntityKind::Document
&& let Some(input) = direct_projection_input_for_object(
@@ -793,6 +839,7 @@ fn projection_partition(typename: &str) -> Option<Token> {
"GraphqlSoupDocument" => Some(vocabulary::document_partition()),
"GraphqlSoupProject" => Some(vocabulary::project_partition()),
"GraphqlSoupChat" => Some(vocabulary::chat_partition()),
+ "GraphqlSoupChannel" => Some(vocabulary::channel_partition()),
_ => None,
}
}
diff --git a/crates/soup_filter_cache_adapter/src/notifications.rs b/crates/soup_filter_cache_adapter/src/notifications.rs
index c27ea38730..5cc3de77e8 100644
--- a/crates/soup_filter_cache_adapter/src/notifications.rs
+++ b/crates/soup_filter_cache_adapter/src/notifications.rs
@@ -110,13 +110,14 @@ fn snapshot_facts(
"GraphqlSoupDocument" => "DOCUMENT",
"GraphqlSoupProject" => "PROJECT",
"GraphqlSoupChat" => "CHAT",
+ "GraphqlSoupChannel" => "CHANNEL",
_ => return Err(()),
};
let mut states = std::collections::BTreeMap::new();
for notification in notifications {
let notification = notification.as_object().ok_or(())?;
// The display edge also contains secondary-entity matches; Soup's SQL
- // predicate for these three partitions only uses primary association.
+ // predicates for these partitions only use primary association.
let primary_id = notification
.get("entityId")
.and_then(serde_json::Value::as_str)
@@ -185,6 +186,7 @@ fn association(record: &Record) -> Option<(RecordKey, Token)> {
"DOCUMENT" => "GraphqlSoupDocument",
"PROJECT" => "GraphqlSoupProject",
"CHAT" => "GraphqlSoupChat",
+ "CHANNEL" => "GraphqlSoupChannel",
_ => return None,
};
uuid::Uuid::parse_str(id).ok()?;
diff --git a/crates/soup_filter_projection/src/channel.rs b/crates/soup_filter_projection/src/channel.rs
new file mode 100644
index 0000000000..ba3758ac92
--- /dev/null
+++ b/crates/soup_filter_projection/src/channel.rs
@@ -0,0 +1,73 @@
+//! Direct channel fields for the general Soup projection profile.
+
+use super::*;
+
+/// Failure to compose direct channel facts.
+#[derive(Debug, Error)]
+pub enum ChannelProjectionError {
+ /// Invalid direct projection data.
+ #[error(transparent)]
+ Direct(#[from] ProjectionError),
+ /// Invalid bounded fact data.
+ #[error(transparent)]
+ Validation(#[from] ValidationError),
+ /// Incomplete or noncanonical channel facts.
+ #[error(transparent)]
+ Profile(#[from] ProfileValidationError),
+}
+
+/// Canonical channel fields already exposed by GraphQL Soup.
+#[derive(Debug, Clone)]
+pub struct ChannelProjectionInput {
+ /// Normalized channel record binding.
+ pub record_key: RecordKey,
+ /// Channel UUID.
+ pub id: uuid::Uuid,
+ /// Channel owner.
+ pub owner: String,
+ /// Canonical public/private/direct_message/team type.
+ pub channel_type: String,
+ /// Optional team UUID.
+ pub team_id: Option<uuid::Uuid>,
+ /// Optional organization ID.
+ pub organization_id: Option<i64>,
+ /// Authoritative viewer-relative active participation.
+ pub is_participant: bool,
+ /// Creation timestamp.
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ /// Content update timestamp.
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+}
+
+/// Project direct channel metadata. The cache adapter must additionally compose
+/// a complete selected active-notification snapshot before establishing coverage.
+pub fn project_channel(
+ input: ChannelProjectionInput,
+) -> Result<IndexDocument, ChannelProjectionError> {
+ let mut facts = common_exact_facts(input.id, input.owner)?;
+ facts.push(utf8_fact(vocabulary::channel_type(), input.channel_type)?);
+ facts.push(ExactFact {
+ attribute: vocabulary::channel_participant(),
+ value: ExactValue::new([u8::from(input.is_participant)])?,
+ });
+ if let Some(team) = input.team_id {
+ facts.push(uuid_fact(vocabulary::channel_team(), team)?);
+ }
+ if let Some(organization) = input.organization_id {
+ facts.push(ExactFact {
+ attribute: vocabulary::channel_organization(),
+ value: ExactValue::new(organization.to_be_bytes())?,
+ });
+ }
+ let mut document = projection(
+ input.record_key,
+ vocabulary::profile_v4(),
+ vocabulary::channel_partition(),
+ facts,
+ input.created_at,
+ input.updated_at,
+ )?;
+ document.canonicalize();
+ validate_soup_flat_v4(&document)?;
+ Ok(document)
+}
diff --git a/crates/soup_filter_projection/src/lib.rs b/crates/soup_filter_projection/src/lib.rs
index 363ca1700f..89aea56b99 100644
--- a/crates/soup_filter_projection/src/lib.rs
+++ b/crates/soup_filter_projection/src/lib.rs
@@ -16,6 +16,7 @@ use predicate_index::{
use soup::domain::models::SoupProjectionHydration;
use thiserror::Error;
+pub mod channel;
mod profile;
mod wire;
diff --git a/crates/soup_filter_projection/src/profile.rs b/crates/soup_filter_projection/src/profile.rs
index fd3d900611..f45d7166f3 100644
--- a/crates/soup_filter_projection/src/profile.rs
+++ b/crates/soup_filter_projection/src/profile.rs
@@ -51,6 +51,7 @@ enum PartitionKind {
Document,
Project,
Chat,
+ Channel,
}
/// Validate strict Soup-specific completeness and canonical value semantics for
@@ -92,6 +93,9 @@ fn validate_soup_flat(
PartitionKind::Project
} else if document.partition == vocabulary::chat_partition() {
PartitionKind::Chat
+ } else if version == ProfileVersion::V4 && document.partition == vocabulary::channel_partition()
+ {
+ PartitionKind::Channel
} else {
return Err(ProfileValidationError::UnsupportedPartition(
document.partition.as_str().to_owned(),
@@ -117,6 +121,10 @@ fn validate_exact_facts(
let mut email_attachment = 0;
let mut importance = 0;
let mut status_options = 0;
+ let mut channel_type = 0;
+ let mut channel_participant = 0;
+ let mut channel_team = 0;
+ let mut channel_organization = 0;
for fact in facts {
let attribute = &fact.attribute;
@@ -131,7 +139,7 @@ fn validate_exact_facts(
if value.is_empty() || std::str::from_utf8(value).is_err() {
return Err(ProfileValidationError::InvalidValue("owner"));
}
- } else if attribute == &vocabulary::project_id() {
+ } else if attribute == &vocabulary::project_id() && kind != PartitionKind::Channel {
project_id += 1;
if value.len() != 16 {
return Err(ProfileValidationError::InvalidValue("project-id"));
@@ -169,6 +177,28 @@ fn validate_exact_facts(
if value.len() != 16 {
return Err(ProfileValidationError::InvalidValue("task-status-option"));
}
+ } else if kind == PartitionKind::Channel && attribute == &vocabulary::channel_type() {
+ channel_type += 1;
+ if !matches!(value, b"public" | b"private" | b"direct_message" | b"team") {
+ return Err(ProfileValidationError::InvalidValue("channel-type"));
+ }
+ } else if kind == PartitionKind::Channel && attribute == &vocabulary::channel_participant()
+ {
+ channel_participant += 1;
+ if !matches!(value, [0] | [1]) {
+ return Err(ProfileValidationError::InvalidValue("channel-participant"));
+ }
+ } else if kind == PartitionKind::Channel && attribute == &vocabulary::channel_team() {
+ channel_team += 1;
+ if value.len() != 16 {
+ return Err(ProfileValidationError::InvalidValue("channel-team"));
+ }
+ } else if kind == PartitionKind::Channel && attribute == &vocabulary::channel_organization()
+ {
+ channel_organization += 1;
+ if value.len() != 8 {
+ return Err(ProfileValidationError::InvalidValue("channel-organization"));
+ }
} else if version == ProfileVersion::V4
&& (attribute == &vocabulary::notification_unseen()
|| attribute == &vocabulary::notification_seen())
@@ -211,6 +241,12 @@ fn validate_exact_facts(
});
}
PartitionKind::Project | PartitionKind::Chat => {}
+ PartitionKind::Channel => {
+ require_one("channel-type", channel_type)?;
+ require_one("channel-participant", channel_participant)?;
+ allow_at_most_one("channel-team", channel_team)?;
+ allow_at_most_one("channel-organization", channel_organization)?;
+ }
}
Ok(())
}
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 8d6dfda405..7af24c13bf 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -23,14 +23,23 @@ Changing filters or resetting the cache discards prior reconciliation evidence.
lists, unsupported filters/sorts, and native/non-cache transports keep their existing
network behavior.
-For Documents (including Tasks), Projects, and Chats, exact `UNSEEN`/`SEEN`
-notification filters also reconcile locally with created/updated timestamp sorts.
+For Documents (including Tasks), Projects, Chats, and participating Channels,
+exact `UNSEEN`/`SEEN` notification filters also reconcile locally with
+created/updated timestamp sorts.
Marking a notification done removes only that notification's contribution immediately;
other active notifications can keep the entity in the list. Seen/reopen operations
update filter membership on the authoritative reply, not from a guessed optimistic
state. Rollback restores only the failed operation's contribution. `DONE` predicates,
other entity partitions, and notified-at sorting still use the network path.
+Channels use the same general Soup reconciliation path, not a separate local page
+chain. Channel ID, type, team, organization, importance, and participant-scoped
+filters operate over synchronized channel metadata. The default channel scope
+requires active participation. Filters that widen to unjoined team channels,
+message sender/mentions, and channel threads remain network-only. Missing channel
+metadata or notification snapshots are unknown, not empty. The existing core
+backfill checkpoint is refreshed to index channel rows; queued work is preserved.
+
Notification facts use the existing active-only GraphQL edge and primary entity
association. Missing/partial or over-budget snapshots remain incomplete, never an
empty notification set; display metadata decoding omissions remain a best-effort