Skip to content

Commit f779531

Browse files
committed
fix(metadata): a bundled type's save writes its own member's row, and loadMany keeps a column-bound package (R4-A, R4-B)
DatabaseLoader.save of a bundled type stored per (package, name) wrote into the slot's first row whatever its member, and on this branch the boot priming pass (MetadataManager.loadMany, then register each) reached it: a two-member slot's en-US row was replaced by fr-FR's body at every boot. The save now targets the row of the member the body declares and inserts a member with no row, naming its bundle_member; an unbundled slotted type keeps one row per slot. MetadataManager.loadMany reads a bundled type through the loader's keyed entries, so a row bound to its package by the package_id column alone keeps that package, and hands the body on stamped with it; a save of a body that differs from its row only by that stamp writes nothing (epic ruling 6799056319). Claude-Session: https://claude.ai/code/session_01QSeKYm8sWjp2Pk76warN7w Co-authored-by: Claude <noreply@anthropic.com>
1 parent f9f589d commit f779531

3 files changed

Lines changed: 159 additions & 6 deletions

File tree

‎packages/metadata/src/loaders/database-loader.test.ts‎

Lines changed: 97 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1707,9 +1707,8 @@ describe('#13997 — stat() emits canonical ISO text whatever the dialect materi
17071707
* (in the set, collapsed one row per name): one alpha bundle answered only
17081708
* `fr-FR`; two packages' bundles answered 1 row of 4.
17091709
*
1710-
* Out of scope: a save through the loader is locale-blind and overwrites
1711-
* another member's row in its slot, as on `main` (card #32422), so the
1712-
* bundles below are seeded as the store writes them.
1710+
* The bundles below are seeded as the store writes them; the save's own
1711+
* member-awareness is pinned in the R4-A describe after this one.
17131712
*/
17141713
describe('[#31699 R3-B] a bundled type keeps every member of every slot', () => {
17151714
const ALPHA = 'com.alpha.app';
@@ -1800,3 +1799,98 @@ describe('[#31699 R3-B] a bundled type keeps every member of every slot', () =>
18001799
expect((await memory.loadManyKeyed('email_template')).map((entry) => entry.name)).toEqual(['welcome', 'welcome']);
18011800
});
18021801
});
1802+
1803+
/**
1804+
* [#31699 R4-A / R4-B, #32422; epic ruling 6799056319] The save of a bundled
1805+
* type stored per `(package, name)` writes the row of the member the body
1806+
* declares, and inserts a member that has no row: never another member's row.
1807+
*
1808+
* BEFORE (measured at f9f589da, same fixtures): the boot priming pass
1809+
* (`MetadataManager.loadMany` then `register` each, as
1810+
* `MetadataPlugin._loadFromFileSystem` does) on a slot holding `en-US` and
1811+
* `fr-FR` replaced the `en-US` row's body with `fr-FR`'s (version 3, a history
1812+
* row); with two packages' rows bound by `package_id` alone, `loadMany`
1813+
* answered alpha's two and the pass inserted a package-less row; a direct save
1814+
* of `fr-FR` into a slot holding `en-US` overwrote the `en-US` row.
1815+
*/
1816+
describe('[#31699 R4-A] the save of a bundled type writes its own member\'s row', () => {
1817+
const ALPHA = 'com.alpha.app';
1818+
const BETA = 'com.beta.app';
1819+
let driver: IDataDriver;
1820+
1821+
const body = (locale: string, packageId: string, stamped: boolean) => ({
1822+
name: 'welcome', locale, subject: `${packageId} ${locale}`, bodyHtml: '<p/>',
1823+
...(stamped ? { _packageId: packageId } : {}),
1824+
});
1825+
// Bound by the `package_id` column; the body stamped or not (the protocol writes none).
1826+
const seed = (packageId: string, locale: string, version: number, stamped: boolean) =>
1827+
driver.create('sys_metadata', {
1828+
id: `${packageId}_${locale}`, type: 'email_template', name: 'welcome', state: 'active', version,
1829+
checksum: `${packageId}_${locale}`, package_id: packageId, bundle_member: locale === 'en-US' ? null : locale,
1830+
metadata: JSON.stringify(body(locale, packageId, stamped)),
1831+
});
1832+
const stored = async (type = 'email_template') =>
1833+
((await driver.find('sys_metadata', { where: { type } } as never)) as Array<Record<string, any>>)
1834+
.map((row) => [row.package_id ?? null, row.bundle_member ?? null, JSON.parse(row.metadata).subject ?? JSON.parse(row.metadata).label])
1835+
.sort((a, b) => String(a).localeCompare(String(b)));
1836+
const manager = () => {
1837+
const m = new MetadataManager({ formats: ['json'], loaders: [] });
1838+
m.registerLoader(new DatabaseLoader({ driver }));
1839+
return m;
1840+
};
1841+
/** `MetadataPlugin._loadFromFileSystem`'s priming pass, over the manager's loaders. */
1842+
const prime = async (m: MetadataManager) => {
1843+
for (const item of (await m.loadMany('email_template')) as Array<{ name?: string }>) {
1844+
if (item?.name) await m.register('email_template', item.name, item, { notify: false });
1845+
}
1846+
};
1847+
1848+
beforeEach(() => {
1849+
driver = createMockDriver();
1850+
});
1851+
1852+
for (const stamped of [true, false]) {
1853+
it(`the priming pass leaves a two-member slot's rows unchanged (bodies ${stamped ? 'stamped' : 'bound by the column only'}; BEFORE: en-US overwritten by fr-FR)`, async () => {
1854+
await seed(ALPHA, 'en-US', 1, stamped);
1855+
await seed(ALPHA, 'fr-FR', 2, stamped);
1856+
const before = await stored();
1857+
await prime(manager());
1858+
expect(await stored()).toEqual(before);
1859+
expect(driver.update).not.toHaveBeenCalled();
1860+
expect(driver.create).toHaveBeenCalledTimes(2);
1861+
});
1862+
}
1863+
1864+
it('R4-B: rows bound by the column only — `loadMany` keeps two packages\' same member apart, and the priming pass writes nothing (BEFORE: alpha\'s two only, and a package-less row inserted)', async () => {
1865+
await seed(ALPHA, 'en-US', 1, false);
1866+
await seed(ALPHA, 'fr-FR', 2, false);
1867+
await seed(BETA, 'en-US', 3, false);
1868+
await seed(BETA, 'fr-FR', 4, false);
1869+
const m = manager();
1870+
const items = (await m.loadMany('email_template')) as Array<{ subject: string; _packageId?: string }>;
1871+
expect(items.map((item) => [item._packageId, item.subject]).sort()).toEqual([
1872+
[ALPHA, `${ALPHA} en-US`], [ALPHA, `${ALPHA} fr-FR`], [BETA, `${BETA} en-US`], [BETA, `${BETA} fr-FR`],
1873+
]);
1874+
const before = await stored();
1875+
await prime(m);
1876+
expect(await stored()).toEqual(before);
1877+
expect(driver.update).not.toHaveBeenCalled();
1878+
expect(driver.create).toHaveBeenCalledTimes(4);
1879+
});
1880+
1881+
it('a direct save of fr-FR into a slot holding en-US inserts the fr-FR row; the en-US row is untouched; a second fr-FR save updates its own row (BEFORE: the en-US row overwritten)', async () => {
1882+
await seed(ALPHA, 'en-US', 1, true);
1883+
const loader = new DatabaseLoader({ driver });
1884+
await loader.save('email_template', 'welcome', body('fr-FR', ALPHA, true));
1885+
expect(await stored()).toEqual([[ALPHA, null, `${ALPHA} en-US`], [ALPHA, 'fr-FR', `${ALPHA} fr-FR`]]);
1886+
await loader.save('email_template', 'welcome', { ...body('fr-FR', ALPHA, true), subject: 'fr again' });
1887+
expect(await stored()).toEqual([[ALPHA, null, `${ALPHA} en-US`], [ALPHA, 'fr-FR', 'fr again']]);
1888+
});
1889+
1890+
it('CONTROL: an unbundled slotted type (agent) still saves to its one row per slot', async () => {
1891+
const loader = new DatabaseLoader({ driver });
1892+
await loader.save('agent', 'helper', { name: 'helper', label: 'v1', _packageId: ALPHA });
1893+
await loader.save('agent', 'helper', { name: 'helper', label: 'v2', _packageId: ALPHA });
1894+
expect(await stored('agent')).toEqual([[ALPHA, null, 'v2']]);
1895+
});
1896+
});

‎packages/metadata/src/loaders/database-loader.ts‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1567,14 +1567,32 @@ export class DatabaseLoader implements MetadataLoader {
15671567
type: string,
15681568
name: string,
15691569
data: unknown,
1570-
): Promise<{ existing: Record<string, unknown> | null; packageId?: string; rows: Array<Record<string, unknown>> }> {
1570+
): Promise<{
1571+
existing: Record<string, unknown> | null;
1572+
packageId?: string;
1573+
rows: Array<Record<string, unknown>>;
1574+
member?: string | null;
1575+
}> {
15711576
const rows = await this._find(this.tableName, { where: this.baseFilter(type, name) });
15721577
const bySlot = new Map<string, Record<string, unknown>>();
15731578
for (const row of rows) {
15741579
const key = storeRowKey(name, storedRowPackageId(row));
15751580
if (!bySlot.has(key)) bySlot.set(key, row);
15761581
}
15771582
const { key, replaces } = storeRowWriteKey(bySlot, type, name, data);
1583+
// [#31699 R4-A, #32422; epic ruling 6799056319] A bundled type's slot holds
1584+
// a row per member: the write goes to the row of the member the body
1585+
// declares (the canonical one spelled `null`, `storedBundleMemberOf`), and
1586+
// a member with no row in the slot is inserted — ⛔ never written over
1587+
// another member's row. The slot itself is chosen from every row of the
1588+
// name, as for every by-package type.
1589+
if (isBundledStoreType(type)) {
1590+
const member = storedBundleMemberOf(type, data) ?? null;
1591+
const rowOf = (slot: string) => rows.find((row) => storeRowKey(name, storedRowPackageId(row)) === slot
1592+
&& (storedBundleMemberOf(type, this.rowToData(row), row.bundle_member) ?? null) === member);
1593+
const existing = rowOf(key) ?? replaces.map(rowOf).find(Boolean) ?? null;
1594+
return { existing, packageId: slotPackageOf(key), rows, member };
1595+
}
15781596
const existing = bySlot.get(key) ?? replaces.map((replaced) => bySlot.get(replaced)).find(Boolean) ?? null;
15791597
return { existing, packageId: slotPackageOf(key), rows };
15801598
}
@@ -1654,7 +1672,7 @@ export class DatabaseLoader implements MetadataLoader {
16541672
// Skip the write when the stored CONTENT is identical (prevents phantom
16551673
// version bumps). [#21828] Content, not stamps: see `storedBodyUnchanged`.
16561674
const previousChecksum = existing.checksum as string | undefined;
1657-
if (storedBodyUnchanged(existing, type, newChecksum)) {
1675+
if (storedBodyUnchanged(existing, type, newChecksum) || (slot?.member !== undefined && onlyBoundStampAdded(existing, type, data, slot.packageId))) {
16581676
// No DB write, but make sure the cached payload reflects the latest
16591677
// call (prior cached `null` would otherwise mask a freshly-saved
16601678
// record). [#32246] An unchanged row written before this loader
@@ -1721,6 +1739,9 @@ export class DatabaseLoader implements MetadataLoader {
17211739
version,
17221740
source: 'database',
17231741
...binding,
1742+
// [#31699 R4-A] A bundled type's new row names its member, as the
1743+
// store's unique key `(type, name, package_id, bundle_member)` reads it.
1744+
...(slot?.member !== undefined ? { bundle_member: slot.member } : {}),
17241745
created_at: now,
17251746
updated_at: now,
17261747
});
@@ -1918,6 +1939,21 @@ function storedBodyUnchanged(row: Record<string, unknown>, type: string, hash: s
19181939
return hashSpec(storedBody, type) === hash;
19191940
}
19201941

1942+
/**
1943+
* [#31699 R4-B] Whether `data` is `row`'s stored body plus nothing but a
1944+
* `_packageId` stamp naming the package `row` is already bound to: the stamp
1945+
* `MetadataManager.loadMany` puts on a body its row binds by the `package_id`
1946+
* column alone. Such a save writes nothing new, so it is no change.
1947+
*/
1948+
function onlyBoundStampAdded(row: Record<string, unknown>, type: string, data: unknown, packageId: string | undefined): boolean {
1949+
if (packageId === undefined || storedRowPackageId(row) !== packageId) return false;
1950+
if (data === null || typeof data !== 'object' || Array.isArray(data)) return false;
1951+
if ((data as Record<string, unknown>)._packageId !== packageId) return false;
1952+
const unstamped: Record<string, unknown> = { ...(data as Record<string, unknown>) };
1953+
delete unstamped._packageId;
1954+
return storedBodyUnchanged(row, type, contentHash(JSON.stringify(unstamped), type));
1955+
}
1956+
19211957
/**
19221958
* Generate a simple unique ID for metadata records.
19231959
* Uses crypto.randomUUID when available, falls back to timestamp-based ID.

‎packages/metadata/src/metadata-manager.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ import { EndpointMatcher } from './endpoint-matcher.js';
8888
import {
8989
PACKAGE_SLOTTED_STORE_TYPES,
9090
bundleEntryKey,
91+
isBundledStoreType,
9192
keyIdentityOf,
9293
readStoreEntry,
9394
recordStoreWrite,
@@ -3335,7 +3336,19 @@ export class MetadataManager implements IMetadataService {
33353336

33363337
for (const loader of this.loaders.values()) {
33373338
try {
3338-
const items = await loader.loadMany<T>(type, options);
3339+
// [#31699 R4-B; epic ruling 6799056319] A bundled type stored per
3340+
// `(package, name)` reads the loader's keyed entries where it has
3341+
// them: a row bound to its package by the `package_id` column alone
3342+
// (as the metadata protocol writes it) carries no stamp in its body,
3343+
// so only the entry's `packageId` keeps two packages' same member
3344+
// apart. Such a body is handed on stamped with that package
3345+
// (`_packageId`, the column's package and only the column's, as the
3346+
// protocol's own read binds a row), so a caller that registers it
3347+
// back — the boot priming pass — fills that package's slot and its
3348+
// member's row, never a package-less one.
3349+
const items = PACKAGE_SLOTTED_STORE_TYPES.has(type) && isBundledStoreType(type) && typeof loader.loadManyKeyed === 'function'
3350+
? (await loader.loadManyKeyed<T>(type, options)).map((entry) => withEntryPackage(entry))
3351+
: await loader.loadMany<T>(type, options);
33393352
for (const item of items) {
33403353
const itemAny = item as any;
33413354
if (itemAny && typeof itemAny.name === 'string') {
@@ -4024,3 +4037,13 @@ export class MetadataManager implements IMetadataService {
40244037
}
40254038
}
40264039

4040+
/**
4041+
* [#31699 R4-B] A keyed entry's body, stamped with the entry's package when the
4042+
* body names none itself; the body unchanged otherwise.
4043+
*/
4044+
function withEntryPackage<T>(entry: MetadataKeyedItem<T>): T {
4045+
const data = entry.data as unknown;
4046+
if (entry.packageId === undefined || indexedItemPackageId(data) !== undefined) return entry.data;
4047+
if (data === null || typeof data !== 'object' || Array.isArray(data)) return entry.data;
4048+
return { ...(data as Record<string, unknown>), _packageId: entry.packageId } as T;
4049+
}

0 commit comments

Comments
 (0)