From 9f3c3388213e87c65329e05a03a6127f35688d01 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:24:47 +0000 Subject: [PATCH 1/3] fix(messaging): the one-time digest conversion rewrites only the snapshot it read before its claim The pass now reads the ids of every row holding digest 'none' in pages by id cursor before claiming its sys_migration row, then rewrites exactly that snapshot. It no longer re-reads where digest = 'none' after each batch, so a 'none' written during the boot pass is a member's real choice and survives. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzi4PechTRCTBrfxV8W --- .../src/preference-digest-conversion.ts | 145 ++++++++++-------- 1 file changed, 85 insertions(+), 60 deletions(-) diff --git a/packages/services/service-messaging/src/preference-digest-conversion.ts b/packages/services/service-messaging/src/preference-digest-conversion.ts index fe290fefed3..7ad5cf7fdbd 100644 --- a/packages/services/service-messaging/src/preference-digest-conversion.ts +++ b/packages/services/service-messaging/src/preference-digest-conversion.ts @@ -36,9 +36,23 @@ * - No ledger on the kernel, or a ledger that cannot be read: the pass does * NOT run, because it could not be recorded and would repeat. * + * ## Only the rows that held `none` before the claim + * + * The pass reads the ids of every row holding `none` FIRST, in pages by id, + * then claims the ledger row, then rewrites exactly that snapshot — it never + * reads the filter again. The deployment is serving while the boot hook + * runs, so a `none` written during the pass (a member's own pick, a new row, + * a node still on the earlier release in a rolling deploy) is a real choice + * and is not part of the snapshot. + * * Every organization's rows: the read is the platform's own, not a tenant's. * Each rewrite is addressed by id AND the stored `none`, under the row's own * organization, so a value written since the read is left alone. + * + * A claim that fails rewrites nothing, and the next boot takes a new + * snapshot: a `none` written between those two boots is converted with the + * rest. Nothing can record the earlier snapshot when the ledger itself cannot + * be written, so that failure is logged as an error naming the fix. */ import type { IDataEngine } from '@objectstack/spec/contracts'; @@ -58,8 +72,8 @@ const LEGACY_UNSET_DIGEST = 'none'; /** The table this conversion rewrites; the type ties it to `PREFERENCE_OBJECT`. */ const OBJECT: typeof PREFERENCE_OBJECT = 'sys_notification_preference'; -/** How many rows one read takes — the same ceiling `PreferenceResolver.loadRows` reads with. */ -const PASS_LIMIT = 10000; +/** How many rows one page of the snapshot read takes. */ +const PAGE_SIZE = 10000; const SYSTEM_CONTEXT = { isSystem: true } as const; @@ -74,15 +88,28 @@ type ConversionEngine = Pick, no } /** - * Rewrite every legacy stored `digest = 'none'` to empty, across every - * organization, unless this deployment's ledger already records the pass. - * Never throws: it runs in a boot hook, which it must not break. + * Rewrite every stored `digest = 'none'` that existed before the ledger claim + * to empty, across every organization, unless this deployment's ledger + * already records the pass. Never throws: it runs in a boot hook, which it + * must not break. */ export async function convertLegacyNoneDigestsOnce( engine: IDataEngine | undefined, logger?: PreferenceDigestConversionLogger, + options: PreferenceDigestConversionOptions = {}, ): Promise { const result = (status: PreferenceDigestConversionResult['status'], converted = 0, failed: string[] = []): PreferenceDigestConversionResult => ({ status, converted, failed }); @@ -151,23 +180,39 @@ export async function convertLegacyNoneDigestsOnce( return result('ledger-unreadable'); } - const readLegacy = async (): Promise>> => { - try { - return ((await e.find( - OBJECT, - { where: { digest: LEGACY_UNSET_DIGEST }, fields: ['id', 'organization_id'], limit: PASS_LIMIT }, - { context: SYSTEM_CONTEXT }, - )) ?? []) as Array>; - } catch (err) { - // No table yet holds no legacy row: a fresh database. - if (isMissingTableError(err, OBJECT)) return []; - throw err; + // The snapshot: every row holding `none` now, read in pages in id order + // until a page comes back short. Taken before the claim, and the only + // rows the pass rewrites. + const size = Math.max(1, Math.floor(options.pageSize ?? PAGE_SIZE)); + const readSnapshot = async (): Promise => { + const snapshot: LegacyRow[] = []; + for (let after: string | undefined; ;) { + let page: Array>; + try { + page = ((await e.find( + OBJECT, + { + where: { digest: LEGACY_UNSET_DIGEST, ...(after === undefined ? {} : { id: { $gt: after } }) }, + fields: ['id', 'organization_id'], + orderBy: [{ field: 'id', order: 'asc' }], + limit: size, + }, + { context: SYSTEM_CONTEXT }, + )) ?? []) as Array>; + } catch (err) { + // No table yet holds no legacy row: a fresh database. + if (after === undefined && isMissingTableError(err, OBJECT)) return []; + throw err; + } + for (const row of page) snapshot.push({ id: String(row.id), organizationId: textOrUndefined(row.organization_id) }); + if (page.length < size) return snapshot; + after = String(page[page.length - 1]!.id); } }; - let rows: Array>; + let rows: LegacyRow[]; try { - rows = await readLegacy(); + rows = await readSnapshot(); } catch (err) { logger?.error( `[messaging] the one-time ${OBJECT} digest conversion could not read the rows it converts, so it did not ` + @@ -207,49 +252,29 @@ export async function convertLegacyNoneDigestsOnce( let converted = 0; const failed: string[] = []; - const seen = new Set(); - // Pass until a read returns no row this run has not already handled. A row - // left as stored still matches the filter, so `seen` is what ends the loop. - for (;;) { - const fresh = rows.filter((row) => !seen.has(String(row.id))); - if (fresh.length === 0) break; - for (const row of fresh) { - const id = String(row.id); - seen.add(id); - try { - // A migration is an entry point, so it states the system - // context itself, with the row's own organization threaded. - // Compare-and-set: the predicate path honours both keys, so a - // digest written since the read is left alone (0 matched). - const matched = await e.update( - OBJECT, - { digest: null }, - { where: { id, digest: LEGACY_UNSET_DIGEST }, multi: true, context: { ...SYSTEM_CONTEXT, tenantId: textOrUndefined(row.organization_id) } }, - ); - if (matched !== 0) converted += 1; - } catch (err) { - failed.push(id); - logger?.error( - `[messaging] the one-time ${OBJECT} digest conversion could not rewrite row ${id} (${messageOf(err)}): ` + - "it still holds the old default digest 'none', which now reads as that person's own choice of no " + - "digest. Fix: open the row in Setup, Notification Preferences, and clear its Digest.", - undefined, - { object: OBJECT, id }, - ); - } - } + // The snapshot only: a row that came to hold `none` after it was taken is + // a choice made under this release, and is never read here. + for (const { id, organizationId } of rows) { try { - rows = await readLegacy(); + // A migration is an entry point, so it states the system + // context itself, with the row's own organization threaded. + // Compare-and-set: the predicate path honours both keys, so a + // digest written since the read is left alone (0 matched). + const matched = await e.update( + OBJECT, + { digest: null }, + { where: { id, digest: LEGACY_UNSET_DIGEST }, multi: true, context: { ...SYSTEM_CONTEXT, tenantId: organizationId } }, + ); + if (matched !== 0) converted += 1; } catch (err) { + failed.push(id); logger?.error( - `[messaging] the one-time ${OBJECT} digest conversion stopped after ${converted} row(s): re-reading the ` + - `rows failed (${messageOf(err)}). It is recorded as run and will not run again, so any row still ` + - "holding digest 'none' reads as that person's own choice of no digest. Fix: clear Digest on those " + - 'rows in Setup, Notification Preferences.', + `[messaging] the one-time ${OBJECT} digest conversion could not rewrite row ${id} (${messageOf(err)}): ` + + "it still holds the old default digest 'none', which now reads as that person's own choice of no " + + "digest. Fix: open the row in Setup, Notification Preferences, and clear its Digest.", undefined, - { object: OBJECT, error: messageOf(err) }, + { object: OBJECT, id }, ); - break; } } From c359746a61edbe3e06b78d996a3d6e4bb8c78177 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:25:17 +0000 Subject: [PATCH 2/3] test(messaging): pin that a none written during the digest conversion survives it Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzi4PechTRCTBrfxV8W --- ...ce-digest-three-states.integration.test.ts | 96 ++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/packages/services/service-messaging/src/preference-digest-three-states.integration.test.ts b/packages/services/service-messaging/src/preference-digest-three-states.integration.test.ts index ee2a9260a84..92e9d609c7e 100644 --- a/packages/services/service-messaging/src/preference-digest-three-states.integration.test.ts +++ b/packages/services/service-messaging/src/preference-digest-three-states.integration.test.ts @@ -9,7 +9,8 @@ * column still carries the old physical DEFAULT 'none' (the temporary * owner-side hook, `preference-digest-unset.ts`, until #36245); * - the legacy `none` nobody chose becomes empty ONCE, across every - * organization, recorded in `sys_migration`; a `none` written after that + * organization, recorded in `sys_migration`; only the rows read before the + * claim are rewritten, so a `none` written during the pass, or after it, * survives every later boot (`preference-digest-conversion.ts`). */ @@ -91,6 +92,29 @@ async function insert(ql: ObjectQL, organization: string, row: Record Promise): never { + let fired = false; + return new Proxy(ql, { + get(target, prop) { + const value = Reflect.get(target, prop, target); + if (typeof value !== 'function') return value; + if (prop !== method) return value.bind(target); + return async (name: string, ...rest: unknown[]) => { + if (name === object && !fired) { + fired = true; + await before(); + } + return (value as (...args: unknown[]) => unknown).call(target, name, ...rest); + }; + }, + }) as never; +} + describe('an upgraded database: the digest column still carries the physical DEFAULT none', () => { it('an insert that leaves the digest unset stores it empty, an explicit none stays none', async () => { const file = dbFile(); @@ -152,6 +176,76 @@ describe('the one-time conversion of the legacy none', () => { expect(await digestOf(second, 'org_a', fresh)).toBe('none'); }); + it('a none written during the pass is not rewritten: only the rows read before the claim are', async () => { + const file = dbFile(); + const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true }); + const old = await insert(legacy, 'org_a', { user_id: 'u1', topic: '*', channel: '*', enabled: true }); + const daily = await insert(legacy, 'org_a', { user_id: 'u2', topic: 'chosen', channel: '*', enabled: true, digest: 'daily' }); + await close(legacy); + + const ql = await boot(file, NotificationPreference, { hook: true }); + let created: string | undefined; + // While the pass is rewriting, the deployment is serving: a new row + // with an explicit none, and a member switching daily to none. + const engine = interceptOnce(ql, 'update', PREF, async () => { + created = await insert(ql, 'org_b', { user_id: 'u2', topic: '*', channel: '*', enabled: true, digest: 'none' }); + await ql.update(PREF, { digest: 'none' }, { where: { id: daily }, ...sys('org_a') } as never); + }); + expect(await convertLegacyNoneDigestsOnce(engine, silent)).toEqual({ status: 'converted', converted: 1, failed: [] }); + expect(created).toBeDefined(); + expect(await digestOf(ql, 'org_a', old)).toBeNull(); + expect(await digestOf(ql, 'org_b', created!)).toBe('none'); + expect(await digestOf(ql, 'org_a', daily)).toBe('none'); + }); + + it('reads the snapshot in pages by id, so every legacy none past the first page is converted', async () => { + const file = dbFile(); + const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true }); + const rows: Array<[string, string]> = []; + for (const [organization, user, topic] of [['org_a', 'u1', '*'], ['org_a', 'u2', '*'], ['org_b', 'u1', '*'], ['org_b', 'u2', '*'], ['org_a', 'u1', 'other']]) { + rows.push([organization, await insert(legacy, organization, { user_id: user, topic, channel: '*', enabled: true })]); + } + await close(legacy); + + const ql = await boot(file, NotificationPreference, { hook: true }); + expect(await convertLegacyNoneDigestsOnce(ql as never, silent, { pageSize: 2 })).toEqual({ status: 'converted', converted: 5, failed: [] }); + for (const [organization, id] of rows) expect(await digestOf(ql, organization, id)).toBeNull(); + }); + + it('a claim that fails after the read rewrites nothing, and leaves no record', async () => { + const file = dbFile(); + const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true }); + const row = await insert(legacy, 'org_a', { user_id: 'u1', topic: '*', channel: '*', enabled: true }); + await close(legacy); + + const ql = await boot(file, NotificationPreference, { hook: true }); + const errors: string[] = []; + const engine = interceptOnce(ql, 'insert', 'sys_migration', async () => { + throw new Error('ledger is read-only'); + }); + const out = await convertLegacyNoneDigestsOnce(engine, { ...silent, error: (m: string) => errors.push(m) }); + expect(out).toEqual({ status: 'claim-failed', converted: 0, failed: [] }); + expect(errors).toHaveLength(1); + expect(await digestOf(ql, 'org_a', row)).toBe('none'); + expect(await ql.findOne('sys_migration', { where: { id: PREFERENCE_DIGEST_NONE_CONVERSION_ID } }, { context: { isSystem: true } as ExecutionContext })).toBeFalsy(); + }); + + it('another node claiming between the read and the claim counts as run, and this pass rewrites nothing', async () => { + const file = dbFile(); + const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true }); + const row = await insert(legacy, 'org_a', { user_id: 'u1', topic: '*', channel: '*', enabled: true }); + await close(legacy); + + const ql = await boot(file, NotificationPreference, { hook: true }); + // The other node's claim lands first; this node's insert of the same + // ledger id is then refused by the store. + const engine = interceptOnce(ql, 'insert', 'sys_migration', async () => { + await ql.insert('sys_migration', { id: PREFERENCE_DIGEST_NONE_CONVERSION_ID, last_run_at: new Date().toISOString(), blocking: 0 }, { context: { isSystem: true } as ExecutionContext }); + }); + expect(await convertLegacyNoneDigestsOnce(engine, silent)).toEqual({ status: 'already-run', converted: 0, failed: [] }); + expect(await digestOf(ql, 'org_a', row)).toBe('none'); + }); + it('without a ledger on the kernel it does not run, so nothing it could not record is rewritten', async () => { const file = dbFile(); const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true, ledger: false }); From 6bd074ceffaca9a695f39b7934767e5fd51263e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:29:06 +0000 Subject: [PATCH 3/3] chore(changeset): the digest conversion rewrites only its pre-claim snapshot Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzi4PechTRCTBrfxV8W --- .changeset/36369-digest-conversion-snapshot.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/36369-digest-conversion-snapshot.md diff --git a/.changeset/36369-digest-conversion-snapshot.md b/.changeset/36369-digest-conversion-snapshot.md new file mode 100644 index 00000000000..fe798c573d5 --- /dev/null +++ b/.changeset/36369-digest-conversion-snapshot.md @@ -0,0 +1,10 @@ +--- +'@objectstack/service-messaging': patch +--- + +fix(messaging): the one-time digest conversion rewrites only the rows that held `none` when it started + +Clause-②: no +Metadata-protocol: none + +The one-time conversion of the old default digest `none` to empty now reads the ids of every row holding `none` first, in pages, then records itself in `sys_migration`, then rewrites exactly those rows. It no longer reads the rows again while it runs. The deployment is already serving during that boot pass, so a `none` someone picks during the pass (a new preference, a member switching to "No digest", a node still on the earlier release in a rolling upgrade) is that person's own choice and is kept. If the conversion cannot record itself in `sys_migration`, it rewrites nothing and runs again on the next start.