fix(mail-index): close handle on every pragma failure, reconcile contact/file deletes

QA pass on the encrypted mail index found two real gaps beyond what the
prior end-to-end fix pass caught:

1. store.ts's MailIndex.open() only wrapped SOME of the post-key pragma
   calls in a try/catch before this: the first attempt's `key` pragma and
   assertEncrypted() ran outside any try at all, and the wrong-key retry
   repeated the same gap. Any pragma throwing there (SQLITE_BUSY, a full
   disk on the first WAL write) leaked the native SQLite handle instead of
   closing it. Factored the open+key+verify+pragma sequence into openKeyed(),
   which guarantees a close before rethrowing on any failure, and reused it
   for both the first attempt and the retry.

2. reindex.ts never removed a deleted contact or file from the index. The
   `removed` field exists in the API and is fully tested at the store layer,
   but nothing in the renderer populates it, so a deleted contact/file stayed
   searchable - and retrievable by the AI feature - indefinitely. Mail and
   calendar can't use the same fix (their queries are date-windowed, so an id
   missing from one fetch may just be outside the window), but contacts/files
   have no date filter - a catch-up fetch that comes back under its cap IS
   the complete set, so anything locally indexed but absent from it is safely
   known to be deleted. Added strayIdsAfterCatchUp() and wired it into the
   catch-up path for those two types only.

Also read binding.ts, key.ts, paths.ts, jmap.ts, extract.ts, the FTS5
query builder, and both /api/offline/{search,reindex} routes end to end;
no other concrete bugs found there. Full findings reported separately.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Bernd Rodler
2026-08-05 23:50:03 +02:00
co-authored by Claude Sonnet 5
parent bde9f14832
commit bde8455df5
4 changed files with 191 additions and 38 deletions
+59 -6
View File
@@ -106,6 +106,26 @@ function isoDaysFromNow(days: number): string {
return new Date(Date.now() + days * 24 * 60 * 60 * 1000).toISOString();
}
/**
* Which locally-indexed ids are stray after an uncapped (contact/file)
* catch-up fetch, and therefore safe to remove as deleted.
*
* Only safe when `queriedCount < cap`: a query that hit the cap was
* truncated - "the rest weren't asked for", not "the rest are gone" - and
* treating a truncated page as the whole world would delete objects that are
* still live. Exported for unit testing; the database-touching caller is not.
*/
export function strayIdsAfterCatchUp(
existingIds: ReadonlySet<string>,
fetchedIds: readonly string[],
queriedCount: number,
cap: number,
): string[] {
if (queriedCount >= cap) return [];
const fetched = new Set(fetchedIds);
return [...existingIds].filter((id) => !fetched.has(id));
}
/**
* Which types this session can actually index. Calendar/contacts are session
* capabilities; files is a PER-ACCOUNT capability (a server can advertise
@@ -151,8 +171,19 @@ interface FetchArgs {
ids: readonly string[] | null;
}
interface FetchResult {
docs: IndexDoc[];
/**
* How many ids the type's OWN query returned, before any `Foo/get`
* chunking. Only set when `ids === null` (a catch-up fetch); used to tell a
* complete uncapped fetch apart from one truncated at its cap - see
* `strayIdsAfterCatchUp`, the only consumer.
*/
queriedCount?: number;
}
/** Fetches and flattens one content type. `ids === null` means "the recent window". */
async function fetchDocs(contentType: ContentType, args: FetchArgs): Promise<IndexDoc[]> {
async function fetchDocs(contentType: ContentType, args: FetchArgs): Promise<FetchResult> {
const { session, authHeader, jmapAccountId, ids } = args;
switch (contentType) {
@@ -170,7 +201,7 @@ async function fetchDocs(contentType: ContentType, args: FetchArgs): Promise<Ind
);
for (const email of emails) docs.push(extractMail(jmapAccountId, email));
}
return docs;
return { docs, queriedCount: ids ? undefined : targetIds.length };
}
case 'calendar': {
const targetIds = ids ?? await queryCalendarEventIds(
@@ -185,7 +216,7 @@ async function fetchDocs(contentType: ContentType, args: FetchArgs): Promise<Ind
);
for (const event of events) docs.push(extractCalendarEvent(jmapAccountId, event));
}
return docs;
return { docs, queriedCount: ids ? undefined : targetIds.length };
}
case 'contact': {
const targetIds = ids ?? await queryContactIds(session, authHeader, jmapAccountId, CONTACTS_MAX);
@@ -196,7 +227,7 @@ async function fetchDocs(contentType: ContentType, args: FetchArgs): Promise<Ind
);
for (const card of cards) docs.push(extractContact(jmapAccountId, card));
}
return docs;
return { docs, queriedCount: ids ? undefined : targetIds.length };
}
case 'file': {
const targetIds = ids ?? await queryFileIds(session, authHeader, jmapAccountId, FILES_MAX);
@@ -208,10 +239,11 @@ async function fetchDocs(contentType: ContentType, args: FetchArgs): Promise<Ind
}
// Paths need the whole set in hand, so this one can't stream per chunk.
const paths = buildFilePaths(nodes);
return nodes
const docs = nodes
// Directories are indexed too: "what's in the Invoices folder" is a
// real query, and a folder row is a few bytes.
.map((node) => extractFile(jmapAccountId, node, { path: paths.get(node.id) }));
return { docs, queriedCount: ids ? undefined : targetIds.length };
}
}
}
@@ -292,7 +324,7 @@ export async function runIndex(
? requestedIds.slice(0, MAX_IDS_PER_CALL)
: null;
const docs = await fetchDocs(contentType, {
const { docs, queriedCount } = await fetchDocs(contentType, {
session, authHeader: indexSession.authHeader, jmapAccountId, ids,
});
written[contentType] = index.upsert(docs);
@@ -302,6 +334,27 @@ export async function runIndex(
// contacts have no date, and file rows are metadata-sized.
index.pruneOlderThan(jmapAccountId, 'mail', isoDaysFromNow(-INDEX_WINDOW_DAYS));
}
// Contact/file DELETES: a JMAP `destroyed` only ever reaches this
// route via `req.removed`, which nothing in the renderer populates
// today - so without this, a deleted contact or file stays
// searchable (and retrievable by the AI feature) forever. Mail and
// calendar can't use the same trick: their queries are windowed by
// date, so an id missing from one fetch may simply be outside the
// window, not gone. Contacts/files have no date filter at all - the
// query is "the first N, capped" - so when a catch-up fetch (ids
// === null) comes back under the cap, it IS the complete set, and
// anything indexed but absent from it is safely known to be deleted.
if (queriedCount !== undefined && (contentType === 'contact' || contentType === 'file')) {
const cap = contentType === 'contact' ? CONTACTS_MAX : FILES_MAX;
const stale = strayIdsAfterCatchUp(
index.existingIds(jmapAccountId, contentType),
docs.map((d) => d.id),
queriedCount,
cap,
);
if (stale.length > 0) index.remove(jmapAccountId, contentType, stale);
}
} catch (error) {
// One unsupported or misbehaving type must not fail the others.
const message = error instanceof Error ? error.message : String(error);