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/perf/mail search (#7271)

Sean Ayec45193c935c9
diff --git a/Cargo.lock b/Cargo.lock
index 657faa7041..2d2d0a655c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3313,7 +3313,7 @@ dependencies = [
[[package]]
name = "cache-wasm"
-version = "0.6.34"
+version = "0.6.35"
dependencies = [
"async-lock",
"cache-core",
diff --git a/apps/web/src/lib/queries/soup/graphql/items.test.ts b/apps/web/src/lib/queries/soup/graphql/items.test.ts
index 6c54941c04..7e8c0039ec 100644
--- a/apps/web/src/lib/queries/soup/graphql/items.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/items.test.ts
@@ -1106,6 +1106,134 @@ describe('createGraphqlSoupAstItemsQuery', () => {
}
});
+ it('accepts a coherent Mail page at a newer revision without repeating the filter scan', async () => {
+ const fake = makeFakeClient();
+ getGraphqlSoupClientMock.mockReturnValue(fake.client);
+ getGraphqlSoupCacheHostMock.mockReturnValue({
+ // Background hydration can advance the engine without a foreground push.
+ currentRevision: vi
+ .fn()
+ .mockResolvedValueOnce(REVISION_0)
+ .mockResolvedValue(REVISION_2),
+ entityFilter: entityFilterMock,
+ onCacheChanged: () => () => {},
+ onCacheGenerationChanged: () => () => {},
+ });
+ makeGraphqlSoupInputMock.mockReturnValue({
+ initial: { emailView: 'ALL', sortMethod: 'UPDATED_AT', limit: 20 },
+ });
+ entityFilterMock.mockResolvedValue({
+ kind: 'mail-page',
+ revision: REVISION_2,
+ keys: [],
+ sortTimestamps: [],
+ nextCursor: null,
+ optimistic: false,
+ });
+ readRecordsByKeysMock.mockResolvedValue({
+ revision: REVISION_2,
+ records: [],
+ });
+ const { query, dispose } = createRoot((dispose) => ({
+ dispose,
+ query: createGraphqlSoupAstItemsQuery(
+ () => ({ params: {}, body: {} }),
+ () => ({ enabled: true })
+ ),
+ }));
+ try {
+ await vi.waitFor(() => expect(query.data()?.cachedMail).toBe(true));
+ expect(entityFilterMock).toHaveBeenCalledTimes(1);
+ expect(readRecordsByKeysMock).toHaveBeenCalledTimes(1);
+ } finally {
+ dispose();
+ }
+ });
+
+ it('keeps a newer non-Mail reconciliation authoritative after reconnect', async () => {
+ const online = vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(true);
+ const fake = makeFakeClient();
+ getGraphqlSoupClientMock.mockReturnValue(fake.client);
+ let revision = REVISION_1;
+ getGraphqlSoupCacheHostMock.mockReturnValue({
+ currentRevision: async () => revision,
+ entityFilter: entityFilterMock,
+ onCacheChanged: () => () => {},
+ onCacheGenerationChanged: () => () => {},
+ });
+ entityFilterMock.mockImplementation(async () => ({
+ kind: 'reconciled',
+ revision,
+ keys: ['GraphqlSoupDocument:item-0'],
+ retainedKeys: [],
+ optimistic: false,
+ }));
+ readRecordsByKeysMock.mockImplementation(async () => ({
+ revision,
+ records: [
+ {
+ recordKey: 'GraphqlSoupDocument:item-0',
+ record: {
+ id: 'item-0',
+ type: 'document',
+ name: 'Hydrated local item',
+ },
+ },
+ ],
+ }));
+ const { query, dispose } = createRoot((dispose) => ({
+ dispose,
+ query: createGraphqlSoupAstItemsQuery(
+ () => ({ params: {}, body: {} }),
+ () => ({ enabled: true })
+ ),
+ }));
+ const names = () => query.data()?.entities.map((item) => item.name);
+ const page = (name: string) =>
+ graphqlSoupPage({
+ items: [{ id: 'item-0', type: 'document', name }],
+ next_cursor: null,
+ });
+ try {
+ fake.executions[0].next(page('Old network item'), {
+ source: 'live-network',
+ revision: REVISION_1,
+ });
+ await vi.waitFor(() => expect(names()).toEqual(['Old network item']));
+
+ // Hydration advances storage without notifying foreground readers.
+ revision = REVISION_2;
+ online.mockReturnValue(false);
+ window.dispatchEvent(new Event('offline'));
+ await vi.waitFor(() => expect(names()).toEqual(['Hydrated local item']));
+ expect(entityFilterMock.mock.calls.at(-1)?.[0]).toHaveProperty(
+ 'baseline'
+ );
+ expect(entityFilterMock.mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'mail'
+ );
+
+ online.mockReturnValue(true);
+ window.dispatchEvent(new Event('online'));
+ // Neither the synchronous publication nor a completed follow-up may
+ // restore revision 1 merely because connectivity returned.
+ expect(names()).toEqual(['Hydrated local item']);
+ await vi.waitFor(() => expect(names()).toEqual(['Hydrated local item']));
+ expect(fake.executions).toHaveLength(1);
+
+ // A genuinely newer network snapshot must still take authority.
+ revision = '3';
+ fake.executions[0].next(page('Fresh network item'), {
+ source: 'live-network',
+ revision,
+ });
+ await vi.waitFor(() => expect(names()).toEqual(['Fresh network item']));
+ } finally {
+ dispose();
+ online.mockRestore();
+ }
+ });
+
it('paginates never-visited Mail filters offline without a server cursor or stale preview timestamps', async () => {
const online = vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(false);
const fake = makeFakeClient();
diff --git a/apps/web/src/lib/queries/soup/graphql/items.ts b/apps/web/src/lib/queries/soup/graphql/items.ts
index e866e252ad..5b58c65032 100644
--- a/apps/web/src/lib/queries/soup/graphql/items.ts
+++ b/apps/web/src/lib/queries/soup/graphql/items.ts
@@ -395,12 +395,15 @@ export function createGraphqlSoupAstItemsQuery(
void (async () => {
const span = Telemetry.span('graphql_cache.soup_local_evaluation');
- let expectedRevision = revision;
let retryCount = 0;
let discarded = false;
let outcome: 'success' | 'incomplete' | 'error' = 'incomplete';
try {
for (let attempt = 0; attempt < 3; attempt += 1) {
+ if (requestId !== localRequest) {
+ discarded = true;
+ return;
+ }
let result = await host.entityFilter({
filters,
sortMethod,
@@ -454,12 +457,10 @@ export function createGraphqlSoupAstItemsQuery(
}
if (
chunks.some((chunk) => result.revision !== chunk.revision) ||
- result.revision !== latestRevision ||
- result.revision !== expectedRevision
+ result.revision !== latestRevision
) {
discarded = true;
retryCount += 1;
- expectedRevision = latestRevision;
setCurrentCacheRevision(latestRevision);
continue;
}
@@ -488,35 +489,42 @@ export function createGraphqlSoupAstItemsQuery(
const item = mapGraphqlSoupItem(record);
return item ? [item] : [];
});
- setLocalProjection({
- input,
- generation: requestGeneration,
- baselineKeys: new Set(
- result.kind === 'mail-page' ? [] : records.map(soupItemKey)
- ),
- displayedKeys: new Set(reconciledRecords.map(soupItemKey)),
- withoutEmail,
- ...(result.kind === 'mail-page'
- ? {
- mail: {
- nextCursor: result.nextCursor,
- revision: result.revision,
- records: reconciledRecords,
- },
- }
- : {}),
- data: {
- cachedMail: result.kind === 'mail-page',
- entities: mapSoupPageToEntityList(
- { items, next_cursor: undefined },
- {
- instructionsIdQuery,
- showSupportedForeignEntities:
- queryOptions.showSupportedForeignEntities,
- }
+ batch(() => {
+ setLocalProjection({
+ input,
+ generation: requestGeneration,
+ baselineKeys: new Set(
+ result.kind === 'mail-page' ? [] : records.map(soupItemKey)
),
- groups: undefined,
- },
+ displayedKeys: new Set(reconciledRecords.map(soupItemKey)),
+ withoutEmail,
+ ...(result.kind === 'mail-page'
+ ? {
+ mail: {
+ nextCursor: result.nextCursor,
+ revision: result.revision,
+ records: reconciledRecords,
+ },
+ }
+ : {}),
+ data: {
+ cachedMail: result.kind === 'mail-page',
+ entities: mapSoupPageToEntityList(
+ { items, next_cursor: undefined },
+ {
+ instructionsIdQuery,
+ showSupportedForeignEntities:
+ queryOptions.showSupportedForeignEntities,
+ }
+ ),
+ groups: undefined,
+ },
+ });
+ // The filter, fragments, and final revision agree. A newer coherent
+ // page is valid even if hydration advanced past the initial read.
+ // Publish both result kinds' watermarks: the Mail guard avoids a
+ // rescan, and reconnect cannot make an older network snapshot authoritative.
+ setCurrentCacheRevision(result.revision);
});
outcome = 'success';
recordAuthority('local');
diff --git a/crates/client/README.md b/crates/client/README.md
index 4938bf96c9..676955ab3f 100644
--- a/crates/client/README.md
+++ b/crates/client/README.md
@@ -136,7 +136,18 @@ projection version do not scan the corpus.
## Local filter execution
-Local SQL materializes Boolean result sets once, but enumerates a universe only
+Single-partition queries first probe at most `max(64, 2 * limit)` sort-index
+candidates from each of the authoritative and optimistic tables. Predicates,
+scope, and shadow suppression are evaluated only for that bounded window. A
+result is accepted only when both windows are exhausted or extend strictly past
+the result's cutoff timestamp, proving that record-key ties are complete. Keyset
+cursors seek inclusively to their timestamp; the full predicate handles ties.
+Sparse matches, truncated ties, and multi-partition queries use the original
+set-based plan in the same read transaction. No schema change or migration is
+required. This keeps dense Mail pages independent of mailbox size without
+changing results or optimistic visibility.
+
+The fallback SQL materializes Boolean result sets once, but enumerates a universe only
within the requested profile and partition. Empty predicates do not enumerate
cached documents. Conjunctions with an indexable positive term filter one scoped
candidate set using document-leading fact probes, rather than materializing every
diff --git a/crates/client/cache-turso/src/storage.rs b/crates/client/cache-turso/src/storage.rs
index d1013a2f64..5226b62716 100644
--- a/crates/client/cache-turso/src/storage.rs
+++ b/crates/client/cache-turso/src/storage.rs
@@ -1482,21 +1482,20 @@ impl PredicateIndexStorage for TursoStorage {
let optimistic = optimistic_query_status(&connection, query)?;
// Incomplete authority and unknown shadows are not candidates, but
// they must not prevent unrelated known-good rows from updating.
- let (sql, parameters) =
- compile_predicate_selection(query, &optimistic.uncertain_ids, true);
- let candidates = driver::query(&connection, &sql, parameters)?
- .into_iter()
- .map(|row| {
- if row.len() != 2 {
- return Err(invariant());
- }
- Ok(predicate_index::ReferenceHit {
- record_key: PredicateRecordKey::new(required_text(&row, 0)?)
- .map_err(|_| invariant())?,
- sort_value: required_i64(&row, 1)?,
+ let candidates =
+ bounded_selection::select(&connection, query, &optimistic.uncertain_ids, true)?
+ .into_iter()
+ .map(|row| {
+ if row.len() != 2 {
+ return Err(invariant());
+ }
+ Ok(predicate_index::ReferenceHit {
+ record_key: PredicateRecordKey::new(required_text(&row, 0)?)
+ .map_err(|_| invariant())?,
+ sort_value: required_i64(&row, 1)?,
+ })
})
- })
- .collect::<Result<Vec<_>, TursoStorageError>>()?;
+ .collect::<Result<Vec<_>, TursoStorageError>>()?;
let keys: Vec<_> = baseline
.iter()
.map(|entry| entry.record_key.clone())
@@ -1594,8 +1593,7 @@ impl PredicateIndexStorage for TursoStorage {
if optimistic.incomplete {
return Ok(PredicateQueryResult::Incomplete);
}
- let (sql, parameters) = compile_predicate_sql(query);
- let rows = driver::query(&connection, &sql, parameters)?;
+ let rows = bounded_selection::select(&connection, query, &[], false)?;
let mut keys = Vec::with_capacity(rows.len());
for row in rows {
if row.len() != 1 {
@@ -4966,6 +4964,7 @@ impl TursoStorage {
}
mod alternatives;
+mod bounded_selection;
mod conjunction;
mod integrity;
mod page_retention;
diff --git a/crates/client/cache-turso/src/storage/bounded_selection.rs b/crates/client/cache-turso/src/storage/bounded_selection.rs
new file mode 100644
index 0000000000..1b4a7b05c3
--- /dev/null
+++ b/crates/client/cache-turso/src/storage/bounded_selection.rs
@@ -0,0 +1,199 @@
+//! Speculative sort-index windows for dense, single-partition filters. Sparse
+//! filters and truncated timestamp ties fall back to the set-based SQL plan.
+//! Both plans run inside the caller's read transaction over the same snapshot.
+
+use super::*;
+use predicate_index::{IndexQuery, ReferenceHit};
+
+const MIN_CANDIDATES: usize = 64;
+const CANDIDATES_PER_RESULT: usize = 2;
+
+pub(super) fn select(
+ connection: &Arc<Connection>,
+ query: &ValidatedIndexQuery,
+ excluded_optimistic: &[i64],
+ include_sort: bool,
+) -> Result<driver::Rows, TursoStorageError> {
+ if let Some(hits) = try_select(connection, query, excluded_optimistic)? {
+ return Ok(hits
+ .into_iter()
+ .map(|hit| {
+ let mut row = vec![text(hit.record_key.as_str())];
+ if include_sort {
+ row.push(Value::from_i64(hit.sort_value));
+ }
+ row
+ })
+ .collect());
+ }
+ let (sql, parameters) = if include_sort {
+ compile_predicate_selection(query, excluded_optimistic, true)
+ } else {
+ compile_predicate_sql(query)
+ };
+ driver::query(connection, &sql, parameters)
+}
+
+fn candidate_budget(query: &IndexQuery) -> usize {
+ (usize::from(query.limit) * CANDIDATES_PER_RESULT).max(MIN_CANDIDATES)
+}
+
+/// Only a positive conjunct constrains the candidate window. Keep the inclusive
+/// timestamp boundary; the full predicate still handles record-key ties exactly.
+fn cursor_bound(expr: &PredicateExpr, query: &IndexQuery) -> Option<i64> {
+ match expr {
+ PredicateExpr::After {
+ attribute,
+ value,
+ direction,
+ ..
+ } if attribute == &query.sort_attribute && direction == &query.sort_direction => {
+ Some(*value)
+ }
+ PredicateExpr::And(left, right) => {
+ match (cursor_bound(left, query), cursor_bound(right, query)) {
+ (Some(left), Some(right)) => Some(match query.sort_direction {
+ SortDirection::Asc => left.max(right),
+ SortDirection::Desc => left.min(right),
+ }),
+ (left, right) => left.or(right),
+ }
+ }
+ _ => None,
+ }
+}
+
+fn candidate_sql(
+ query: &IndexQuery,
+ source: conjunction::FactSource,
+ excluded_optimistic: &[i64],
+) -> (String, Vec<Value>) {
+ let (facts, index, documents) = match source {
+ conjunction::FactSource::Authority => {
+ ("sort_facts", "sort_facts_lookup_idx", "index_documents")
+ }
+ conjunction::FactSource::Optimistic => (
+ "optimistic_sort_facts",
+ "optimistic_sort_facts_lookup_idx",
+ "optimistic_index_documents",
+ ),
+ };
+ let direction = match query.sort_direction {
+ SortDirection::Asc => "ASC",
+ SortDirection::Desc => "DESC",
+ };
+ let mut parameters = vec![text(query.sort_attribute.as_str())];
+ let boundary = if let Some(value) = cursor_bound(&query.partitions[0].predicate, query) {
+ parameters.push(Value::from_i64(value));
+ match query.sort_direction {
+ SortDirection::Asc => " AND value >= ?",
+ SortDirection::Desc => " AND value <= ?",
+ }
+ } else {
+ ""
+ };
+ parameters.extend([
+ Value::from_i64(candidate_budget(query) as i64),
+ text(query.profile.token().as_str()),
+ text(query.partitions[0].partition.as_str()),
+ ]);
+ let shadow = match source {
+ // Any shadow suppresses authority, even a deleted, uncertain, or moved one.
+ conjunction::FactSource::Authority => " AND NOT EXISTS (SELECT 1 FROM optimistic_index_documents AS o WHERE o.record_key = d.record_key)".to_owned(),
+ conjunction::FactSource::Optimistic if !excluded_optimistic.is_empty() => {
+ parameters.extend(excluded_optimistic.iter().copied().map(Value::from_i64));
+ format!(" AND d.id NOT IN ({})", vec!["?"; excluded_optimistic.len()].join(", "))
+ }
+ conjunction::FactSource::Optimistic => String::new(),
+ };
+ let predicate = conjunction::condition(&query.partitions[0].predicate, source, &mut parameters);
+ // Bound BEFORE scope/predicate probes. A sparse query cannot turn this
+ // speculation into a full-index walk. Ordering document_id with value lets
+ // Turso walk the existing index without sorting the corpus. Record-key
+ // ordering is resolved only after proving the entire cutoff tie is present.
+ let sql = format!(
+ "WITH candidates AS MATERIALIZED (SELECT document_id, value FROM {facts} INDEXED BY {index} WHERE attribute = ?{boundary} ORDER BY value {direction}, document_id {direction} LIMIT ?) SELECT d.record_key, s.value, CASE WHEN d.profile = ? AND d.partition = ? AND d.state = 0{shadow} AND ({predicate}) THEN 1 ELSE 0 END FROM candidates AS s CROSS JOIN {documents} AS d ON d.id = s.document_id"
+ );
+ (sql, parameters)
+}
+
+struct Window {
+ exhausted: bool,
+ frontier: Option<i64>,
+}
+
+fn try_select(
+ connection: &Arc<Connection>,
+ query: &ValidatedIndexQuery,
+ excluded_optimistic: &[i64],
+) -> Result<Option<Vec<ReferenceHit>>, TursoStorageError> {
+ let query = query.as_query();
+ if query.partitions.len() != 1 || matches!(query.partitions[0].predicate, PredicateExpr::None) {
+ return Ok(None);
+ }
+ let mut hits = Vec::new();
+ let mut windows = Vec::new();
+ for source in [
+ conjunction::FactSource::Authority,
+ conjunction::FactSource::Optimistic,
+ ] {
+ let (sql, parameters) = candidate_sql(query, source, excluded_optimistic);
+ let rows = driver::query(connection, &sql, parameters)?;
+ let mut window = Window {
+ exhausted: rows.len() < candidate_budget(query),
+ frontier: None,
+ };
+ for row in rows {
+ if row.len() != 3 {
+ return Err(invariant());
+ }
+ let sort_value = required_i64(&row, 1)?;
+ window.frontier = Some(match window.frontier {
+ None => sort_value,
+ Some(previous) => match query.sort_direction {
+ SortDirection::Asc => previous.max(sort_value),
+ SortDirection::Desc => previous.min(sort_value),
+ },
+ });
+ if required_i64(&row, 2)? == 1 {
+ hits.push(ReferenceHit {
+ record_key: PredicateRecordKey::new(required_text(&row, 0)?)
+ .map_err(|_| invariant())?,
+ sort_value,
+ });
+ }
+ }
+ windows.push(window);
+ }
+ hits.sort_by(|left, right| {
+ let value = match query.sort_direction {
+ SortDirection::Asc => left.sort_value.cmp(&right.sort_value),
+ SortDirection::Desc => right.sort_value.cmp(&left.sort_value),
+ };
+ value.then_with(|| match query.tie_break_direction {
+ SortDirection::Asc => left.record_key.cmp(&right.record_key),
+ SortDirection::Desc => right.record_key.cmp(&left.record_key),
+ })
+ });
+ let limit = usize::from(query.limit);
+ let cutoff = hits.get(limit - 1).map(|hit| hit.sort_value);
+ for window in windows {
+ if window.exhausted {
+ continue;
+ }
+ let covered = cutoff
+ .zip(window.frontier)
+ .is_some_and(|(cutoff, frontier)| match query.sort_direction {
+ SortDirection::Asc => frontier > cutoff,
+ SortDirection::Desc => frontier < cutoff,
+ });
+ if !covered {
+ return Ok(None);
+ }
+ }
+ hits.truncate(limit);
+ Ok(Some(hits))
+}
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod test;
diff --git a/crates/client/cache-turso/src/storage/bounded_selection/test.rs b/crates/client/cache-turso/src/storage/bounded_selection/test.rs
new file mode 100644
index 0000000000..803acf81d9
--- /dev/null
+++ b/crates/client/cache-turso/src/storage/bounded_selection/test.rs
@@ -0,0 +1,379 @@
+use super::*;
+use crate::storage::test::{authoritative_projection, queued};
+use pollster::block_on;
+use predicate_index::{ExactValue, IndexDocument, PartitionPredicate, evaluate_reference};
+
+fn query(
+ predicate: PredicateExpr,
+ direction: SortDirection,
+ tie: SortDirection,
+) -> ValidatedIndexQuery {
+ ValidatedIndexQuery::new(IndexQuery {
+ profile: Profile::new(Token::new("profile-v1").unwrap()),
+ partitions: vec![PartitionPredicate {
+ partition: Token::new("thing").unwrap(),
+ predicate,
+ }],
+ sort_attribute: Token::new("updated-at").unwrap(),
+ sort_direction: direction,
+ tie_break_direction: tie,
+ limit: 20,
+ })
+ .unwrap()
+}
+
+fn owner(value: &str) -> PredicateExpr {
+ PredicateExpr::Exact {
+ attribute: Token::new("owner").unwrap(),
+ value: ExactValue::utf8(value).unwrap(),
+ }
+}
+
+fn document(n: u32, timestamp: i64) -> IndexDocument {
+ let mut doc = authoritative_projection(&format!("Thing:{n:05}"), "owner");
+ doc.sort_facts[0].value = timestamp;
+ doc
+}
+
+fn hits(
+ connection: &Arc<Connection>,
+ query: &ValidatedIndexQuery,
+ excluded: &[i64],
+) -> Vec<(String, i64)> {
+ select(connection, query, excluded, true)
+ .unwrap()
+ .iter()
+ .map(|row| {
+ (
+ required_text(row, 0).unwrap(),
+ required_i64(row, 1).unwrap(),
+ )
+ })
+ .collect()
+}
+
+fn reference(
+ connection: &Arc<Connection>,
+ query: &ValidatedIndexQuery,
+ excluded: &[i64],
+) -> Vec<(String, i64)> {
+ let (sql, parameters) = compile_predicate_selection(query, excluded, true);
+ driver::query(connection, &sql, parameters)
+ .unwrap()
+ .iter()
+ .map(|row| {
+ (
+ required_text(row, 0).unwrap(),
+ required_i64(row, 1).unwrap(),
+ )
+ })
+ .collect()
+}
+
+#[test]
+fn dense_pages_have_a_corpus_independent_vm_budget() {
+ block_on(async {
+ for count in [1_000, 5_000] {
+ let mut storage = TursoStorage::open_in_memory("bounded-dense").unwrap();
+ storage
+ .put_batch_with_projections(
+ Vec::new(),
+ (0..count)
+ .map(|n| ProjectionMutation::Replace(document(n, i64::from(n))))
+ .collect(),
+ )
+ .await
+ .unwrap();
+ let predicate = PredicateExpr::And(
+ Box::new(owner("owner")),
+ Box::new(PredicateExpr::Not(Box::new(owner("excluded")))),
+ );
+ for direction in [SortDirection::Asc, SortDirection::Desc] {
+ let query = query(predicate.clone(), direction, direction);
+ let (sql, parameters) =
+ candidate_sql(query.as_query(), conjunction::FactSource::Authority, &[]);
+ let mut statement = driver::prepare(&storage.connection(), &sql).unwrap();
+ let rows = driver::query_prepared(&mut statement, parameters).unwrap();
+ assert_eq!(rows.len(), MIN_CANDIDATES);
+ assert!(
+ statement.metrics().vm_steps < 20_000,
+ "{count} records: {} VM steps",
+ statement.metrics().vm_steps
+ );
+ assert!(
+ try_select(&storage.connection(), &query, &[])
+ .unwrap()
+ .is_some()
+ );
+ assert_eq!(
+ hits(&storage.connection(), &query, &[]),
+ reference(&storage.connection(), &query, &[])
+ );
+ let first = hits(&storage.connection(), &query, &[]);
+ let (key, value) = first.last().unwrap();
+ let next = query
+ .after(*value, PredicateRecordKey::new(key.clone()).unwrap())
+ .unwrap();
+ assert!(
+ try_select(&storage.connection(), &next, &[])
+ .unwrap()
+ .is_some()
+ );
+ assert_eq!(
+ hits(&storage.connection(), &next, &[]),
+ reference(&storage.connection(), &next, &[])
+ );
+ }
+ }
+ });
+}
+
+#[test]
+fn ties_sparse_matches_and_unrelated_scopes_fall_back_without_losing_results() {
+ block_on(async {
+ let mut storage = TursoStorage::open_in_memory("bounded-fallback").unwrap();
+ let docs = (0..200)
+ .rev()
+ .map(|n| {
+ let mut doc = document(n, 5);
+ if n < 10 {
+ doc.exact_facts[0].value = ExactValue::utf8("rare").unwrap();
+ }
+ if n % 4 == 0 {
+ doc.profile = Profile::new(Token::new("other").unwrap());
+ }
+ if n % 7 == 0 {
+ doc.partition = Token::new("other").unwrap();
+ }
+ if n % 11 == 0 {
+ doc.sort_facts.clear();
+ }
+ doc
+ })
+ .collect::<Vec<_>>();
+ storage
+ .put_batch_with_projections(
+ Vec::new(),
+ docs.iter()
+ .cloned()
+ .map(ProjectionMutation::Replace)
+ .collect(),
+ )
+ .await
+ .unwrap();
+ for direction in [SortDirection::Asc, SortDirection::Desc] {
+ for tie in [SortDirection::Asc, SortDirection::Desc] {
+ for predicate in [
+ PredicateExpr::All,
+ owner("rare"),
+ PredicateExpr::Not(Box::new(owner("rare"))),
+ PredicateExpr::None,
+ ] {
+ let query = query(predicate, direction, tie);
+ assert!(
+ try_select(&storage.connection(), &query, &[])
+ .unwrap()
+ .is_none()
+ );
+ let expected = evaluate_reference(&query, &docs)
+ .into_iter()
+ .map(|hit| (hit.record_key.as_str().to_owned(), hit.sort_value))
+ .collect::<Vec<_>>();
+ assert_eq!(hits(&storage.connection(), &query, &[]), expected);
+ if let Some((key, value)) = expected.last() {
+ let next = query
+ .after(*value, PredicateRecordKey::new(key.clone()).unwrap())
+ .unwrap();
+ assert_eq!(
+ hits(&storage.connection(), &next, &[]),
+ reference(&storage.connection(), &next, &[])
+ );
+ }
+ }
+ }
+ }
+ });
+}
+
+#[test]
+fn complete_cutoff_ties_use_record_keys_not_internal_document_ids() {
+ block_on(async {
+ let mut storage = TursoStorage::open_in_memory("bounded-ties").unwrap();
+ let docs = (0..200)
+ .rev()
+ .map(|n| document(n, i64::from(n / 7)))
+ .collect::<Vec<_>>();
+ storage
+ .put_batch_with_projections(
+ Vec::new(),
+ docs.iter()
+ .cloned()
+ .map(ProjectionMutation::Replace)
+ .collect(),
+ )
+ .await
+ .unwrap();
+ for direction in [SortDirection::Asc, SortDirection::Desc] {
+ for tie in [SortDirection::Asc, SortDirection::Desc] {
+ let query = query(PredicateExpr::All, direction, tie);
+ assert!(
+ try_select(&storage.connection(), &query, &[])
+ .unwrap()
+ .is_some()
+ );
+ let first = hits(&storage.connection(), &query, &[]);
+ assert_eq!(first, reference(&storage.connection(), &query, &[]));
+ let (key, value) = first.last().unwrap();
+ let next = query
+ .after(*value, PredicateRecordKey::new(key.clone()).unwrap())
+ .unwrap();
+ assert!(
+ try_select(&storage.connection(), &next, &[])
+ .unwrap()
+ .is_some()
+ );
+ assert_eq!(
+ hits(&storage.connection(), &next, &[]),
+ reference(&storage.connection(), &next, &[])
+ );
+ }
+ }
+ });
+}
+
+#[test]
+fn optimistic_moves_deletes_and_uncertainty_suppress_authority() {
+ block_on(async {
+ let mut storage = TursoStorage::open_in_memory("bounded-shadows").unwrap();
+ storage
+ .put_batch_with_projections(
+ Vec::new(),
+ (0..120)
+ .map(|n| ProjectionMutation::Replace(document(n, i64::from(n))))
+ .collect(),
+ )
+ .await
+ .unwrap();
+ let complete = |document| PendingOptimisticProjection {
+ state: OptimisticProjectionState::Complete(document),
+ uncertainty: OptimisticUncertainty::Attributes(BTreeSet::new()),
+ };
+ let mut moved = document(119, 119);
+ moved.partition = Token::new("other").unwrap();
+ let mut missing_sort = document(118, 118);
+ missing_sort.sort_facts.clear();
+ storage
+ .enqueue_mutation_with_shadow(
+ queued("Bounded"),
+ vec![
+ complete(moved),
+ complete(missing_sort),
+ complete(document(117, -10)),
+ PendingOptimisticProjection {
+ state: OptimisticProjectionState::Deleted {
+ record_key: document(116, 116).record_key,
+ profile: Profile::new(Token::new("profile-v1").unwrap()),
+ partition: Token::new("thing").unwrap(),
+ },
+ uncertainty: OptimisticUncertainty::Attributes(BTreeSet::new()),
+ },
+ PendingOptimisticProjection {
+ state: OptimisticProjectionState::Complete(document(115, 1000)),
+ uncertainty: OptimisticUncertainty::Attributes(
+ [Token::new("owner").unwrap()].into(),
+ ),
+ },
+ complete(document(200, 999)),
+ ],
+ )
+ .await
+ .unwrap();
+ let query = query(owner("owner"), SortDirection::Desc, SortDirection::Asc);
+ let status = optimistic_query_status(&storage.connection(), &query).unwrap();
+ assert_eq!(status.uncertain_ids.len(), 1);
+ assert!(
+ try_select(&storage.connection(), &query, &status.uncertain_ids)
+ .unwrap()
+ .is_some()
+ );
+ let actual = hits(&storage.connection(), &query, &status.uncertain_ids);
+ assert_eq!(
+ actual,
+ reference(&storage.connection(), &query, &status.uncertain_ids)
+ );
+ assert_eq!(actual[0], ("Thing:00200".to_owned(), 999));
+ assert!(actual.iter().all(|(key, _)| {
+ ![
+ "Thing:00115",
+ "Thing:00116",
+ "Thing:00117",
+ "Thing:00118",
+ "Thing:00119",
+ ]
+ .contains(&key.as_str())
+ }));
+ let result = storage
+ .reconcile_predicate_index(&query, &[])
+ .await
+ .unwrap();
+ assert_eq!(
+ result
+ .keys
+ .iter()
+ .map(|key| key.as_str())
+ .collect::<Vec<_>>(),
+ actual
+ .iter()
+ .map(|(key, _)| key.as_str())
+ .collect::<Vec<_>>()
+ );
+ });
+}
+
+#[test]
+fn exhausted_windows_and_multi_partition_queries_match_the_original_plan() {
+ block_on(async {
+ let mut storage = TursoStorage::open_in_memory("bounded-exhausted").unwrap();
+ for count in [0, 5] {
+ storage
+ .put_batch_with_projections(
+ Vec::new(),
+ (0..count)
+ .map(|n| ProjectionMutation::Replace(document(n, i64::from(n))))
+ .collect(),
+ )
+ .await
+ .unwrap();
+ let one = query(PredicateExpr::All, SortDirection::Desc, SortDirection::Desc);
+ assert!(
+ try_select(&storage.connection(), &one, &[])
+ .unwrap()
+ .is_some()
+ );
+ assert_eq!(
+ hits(&storage.connection(), &one, &[]),
+ reference(&storage.connection(), &one, &[])
+ );
+ let mut descriptor = one.as_query().clone();
+ descriptor.partitions.push(PartitionPredicate {
+ partition: Token::new("other").unwrap(),
+ predicate: PredicateExpr::All,
+ });
+ let multi = ValidatedIndexQuery::new(descriptor).unwrap();
+ assert!(
+ try_select(&storage.connection(), &multi, &[])
+ .unwrap()
+ .is_none()
+ );
+ assert_eq!(
+ hits(&storage.connection(), &multi, &[]),
+ reference(&storage.connection(), &multi, &[])
+ );
+ let direct = storage.query_predicate_index(&one).await.unwrap();
+ let PredicateQueryResult::Complete(keys) = direct else {
+ panic!("expected complete page")
+ };
+ assert_eq!(keys.len(), count as usize);
+ }
+ });
+}
diff --git a/crates/client/cache-turso/src/storage/test.rs b/crates/client/cache-turso/src/storage/test.rs
index 62b231fe83..1e289322f2 100644
--- a/crates/client/cache-turso/src/storage/test.rs
+++ b/crates/client/cache-turso/src/storage/test.rs
@@ -51,7 +51,7 @@ fn quick_access_document(name: &str, timestamp: u64) -> Record {
document
}
-fn queued(label: &str) -> NewQueuedMutation {
+pub(super) fn queued(label: &str) -> NewQueuedMutation {
NewQueuedMutation {
uuid: uuid::Uuid::new_v4(),
mutation: StoredMutation::new(
@@ -94,7 +94,7 @@ fn pending_projection(key: &str, owner: &str, updated_at: i64) -> PendingOptimis
}
}
-fn authoritative_projection(key: &str, owner: &str) -> predicate_index::IndexDocument {
+pub(super) fn authoritative_projection(key: &str, owner: &str) -> predicate_index::IndexDocument {
let token = |value| Token::new(value).unwrap();
predicate_index::IndexDocument {
record_key: PredicateRecordKey::new(key).unwrap(),
diff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.toml
index 191219d1eb..834a4d231b 100644
--- a/crates/client/cache-wasm/Cargo.toml
+++ b/crates/client/cache-wasm/Cargo.toml
@@ -2,8 +2,8 @@
edition = "2024"
name = "cache-wasm"
publish = false
-# Rebuild for bucket-scoped search catalogs and bounded borrowed ranking.
-version = "0.6.34"
+# Rebuild for bounded sort-index selection of dense local filter pages.
+version = "0.6.35"
[features]
default = []
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 1d62c70a00..954ced7af9 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -75,6 +75,10 @@ visible; local results do not trigger the tab-loading bar. A fresh server respon
still replaces that result, and initial loads without usable data retain normal loading
indicators. A transport failure does not hide usable current-query local results,
including empty results; HTTP responses and GraphQL errors still surface.
+To check reconnect behavior, load a non-Mail list online, let background hydration
+advance its cache while offline, then reconnect without delivering a fresh network
+response. The newer local result must remain visible; connectivity alone must not
+restore the older network snapshot. A fresh network response can take authority again.
This is a best-effort display, not proof that every matching entity is cached. Outside
the supported cached-Mail slice below, loading more follows the original server cursors
@@ -464,6 +468,14 @@ native offline archive support therefore requires a full app build, not just OTA
### Cached Mail filtering
+Performance check: switch Signal → All twice against a large synchronized cache.
+Dense local pages use bounded sort-index candidates rather than sorting the entire
+mailbox. Sparse filters and large timestamp ties retain the exact fallback plan.
+A filter result, row fragments, and final revision that agree must be accepted even
+when background hydration advanced past the revision observed before the request;
+that alone must not trigger another filter scan. Also verify local Load more,
+same-timestamp ordering, and pending archive/read changes.
+
With GraphQL caching enabled (browser or native Tauri) and the email metadata backfill synchronized,
All, Signal, Noise, Drafts, Sent, Calendar, and Shared support tab changes and new
filter combinations while offline: account selection