Skip to content

Commit 0f93f8f

Browse files
committed
fix(metadata): the boot priming pass never writes an item back into the loader it read it from (R5-A)
The pass (MetadataPlugin._loadFromFileSystem: loadMany, then register each) persisted every item it read back into every datasource loader, the one it came from included, so each stored shape the save resolved differently from its own row was rewritten at boot: a package's en-US row beside a package-less en-US row took the package-less body, and a package-less fr-FR row was copied into the package's slot. loadMany now records the loader each item object came from, and register with skipSourceLoader skips that loader's write-through only; an item read from another loader still seeds the database loader (epic ruling 6801410166). Claude-Session: https://claude.ai/code/session_01QSeKYm8sWjp2Pk76warN7w Co-authored-by: Claude <noreply@anthropic.com>
1 parent cfb8f30 commit 0f93f8f

4 files changed

Lines changed: 92 additions & 3 deletions

File tree

‎.changeset/31699-email-template-names-per-namespace.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ The bare-name one-holder rule (`bare-name-one-holder.ts`) has narrowed for `emai
2626
- The flow `notify` node records the package whose own flow body is armed (`AutomationEngine.flowCallerPackage`, now public) beside its template reference (`template:`, or a template named in the node's literal `payload.template`, which the channels read alike), as the delivery payload's `templateCallerPackageId`; the email and inbox channels hand it to the send. An environment-authored flow, or an environment override of a packaged one, records none; a `templateCallerPackageId` key in the node's literal `payload` is dropped, never forwarded. A delivery row queued before this release carries no such key and sends as before, with no package.
2727

2828
- `MetadataManager`'s in-memory store keeps one slot per `(package, name)` for `email_template` (`PACKAGE_SLOTTED_STORE_TYPES` in `@objectstack/metadata`, now `api`, `agent`, `skill`, `action`, `email_template` and `permission`): two packages' templates of one name both stay in it, `get(type, name, packageId)` answers that package's own (never another package's), and `get` naming no package of a two-holder name refuses `409` naming both (D3), where the second package's item overwrote the first's. The loaders follow the same rules (`DatabaseLoader`, `MemoryLoader`): a save fills `package_id`; a rollback and a delete by name are refused as (5) and (6) state; and their unscoped reads keep every member of every slot (one row per `(package, name, member)`, the canonical locale stored as `bundle_member` NULL), so no locale of any package's bundle is dropped. `MetadataManager.loadMany` and `loadManyKeyed` likewise answer one entry per `(package, name, member)` for an email template, where they answered one per name; `loadMany` reads a row's package from its `package_id` column when the body carries no stamp, and hands such a body on stamped with it (`_packageId`).
29-
- The database loader's save of an email template (`DatabaseLoader.save`) writes the row of the member the body declares, FROM the slot's first row whatever its locale (so a save of `fr-FR` replaced the stored `en-US` body, and a boot's priming pass, which registers every stored member back, did so at every boot) TO that member's own row, inserting it with its `bundle_member` when the slot has none. It never writes over another member's row. A save whose body differs from its row only by a `_packageId` stamp naming the row's own package writes nothing. Every other type stored per `(package, name)` keeps one row per slot. Not a refusal: no write that succeeded before is refused.
29+
- The database loader's save of an email template (`DatabaseLoader.save`) writes the row of the member the body declares, FROM the slot's first row whatever its locale (so a save of `fr-FR` replaced the stored `en-US` body, and a boot's priming pass, which registers every stored member back, did so at every boot) TO that member's own row, inserting it with its `bundle_member` when the slot has none. It never writes over another member's row. A save whose body differs from its row only by a `_packageId` stamp naming the row's own package writes nothing. Every other type stored per `(package, name)` keeps one row per slot. Not a refusal: no write that succeeded before is refused. A boot no longer writes back rows it read from the same loader: the priming pass registers each stored item without saving it into the loader it was read from (`MetadataManager.register`'s `skipSourceLoader`), and an item read from another loader still seeds the database loader.
3030

3131
So a package no longer has to rename an email template because a package of another namespace already ships one of that name, and each package's flows keep sending their own.
3232

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

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { DatabaseLoader } from './database-loader.js';
55
import type { IDataDriver } from '@objectstack/spec/contracts';
66
import { MetadataManager } from '../metadata-manager.js';
77
import { MemoryLoader } from './memory-loader.js';
8+
import { MetadataPlugin } from '../plugin.js';
89

910
// Suppress logger output during tests. Stable object (not a fresh one per
1011
// `createLogger()` call) so the #5108 block can assert on what `list()` says
@@ -1894,3 +1895,68 @@ describe('[#31699 R4-A] the save of a bundled type writes its own member\'s row'
18941895
expect(await stored('agent')).toEqual([[ALPHA, null, 'v2']]);
18951896
});
18961897
});
1898+
1899+
/**
1900+
* [#31699 R5-A; epic ruling 6801410166] The boot priming pass
1901+
* (`MetadataPlugin._loadFromFileSystem`, run for real here over a
1902+
* `DatabaseLoader`) never writes an item back into the loader it read it from;
1903+
* an item read from another loader still seeds the database loader.
1904+
*
1905+
* BEFORE (measured at cfb8f300, same fixtures): a package's `en-US` row beside
1906+
* a package-less `en-US` row was overwritten with the package-less body
1907+
* (version 3, one update); beside a package-less `fr-FR` row, a package-bound
1908+
* copy of it was inserted; a non-`datasource:` loader's item seeded one row.
1909+
*/
1910+
describe('[#31699 R5-A] the priming pass never writes back a row it read from the same loader', () => {
1911+
const ALPHA = 'com.alpha.app';
1912+
let driver: IDataDriver;
1913+
const seed = (id: string, packageId: string | null, locale: string, subject: string) =>
1914+
driver.create('sys_metadata', {
1915+
id, type: 'email_template', name: 'welcome', state: 'active', version: 1, checksum: id,
1916+
package_id: packageId, bundle_member: locale === 'en-US' ? null : locale,
1917+
metadata: JSON.stringify({ name: 'welcome', locale, subject, bodyHtml: '<p/>' }),
1918+
});
1919+
const stored = async () =>
1920+
((await driver.find('sys_metadata', { where: { type: 'email_template' } } as never)) as Array<Record<string, any>>)
1921+
.map((row) => [row.package_id ?? null, row.bundle_member ?? null, JSON.parse(row.metadata).subject])
1922+
.sort((a, b) => String(a).localeCompare(String(b)));
1923+
/** The real pass, over exactly `loaders` (the manager's default loaders removed). */
1924+
const bootPass = async (...loaders: Array<DatabaseLoader | MemoryLoader>) => {
1925+
const plugin = new MetadataPlugin({ watch: false, config: { bootstrap: 'eager' } });
1926+
const manager = (plugin as any).manager as MetadataManager;
1927+
(manager as any).loaders.clear();
1928+
for (const loader of loaders) manager.registerLoader(loader);
1929+
await (plugin as any)._loadFromFileSystem({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } });
1930+
};
1931+
1932+
beforeEach(() => {
1933+
driver = createMockDriver();
1934+
});
1935+
1936+
it('a package\'s en-US row beside a package-less en-US row: both unchanged, no update, no insert (BEFORE: the package\'s row overwritten)', async () => {
1937+
await seed('alpha_en', ALPHA, 'en-US', 'alpha own');
1938+
await seed('env_en', null, 'en-US', 'env older');
1939+
const before = await stored();
1940+
await bootPass(new DatabaseLoader({ driver }));
1941+
expect(await stored()).toEqual(before);
1942+
expect(driver.update).not.toHaveBeenCalled();
1943+
expect(driver.create).toHaveBeenCalledTimes(2);
1944+
});
1945+
1946+
it('the member-absent neighbour: a package\'s en-US row beside a package-less fr-FR row inserts nothing (BEFORE: a package-bound fr-FR copy inserted)', async () => {
1947+
await seed('alpha_en', ALPHA, 'en-US', 'alpha own');
1948+
await seed('env_fr', null, 'fr-FR', 'env fr');
1949+
const before = await stored();
1950+
await bootPass(new DatabaseLoader({ driver }));
1951+
expect(await stored()).toEqual(before);
1952+
expect(driver.update).not.toHaveBeenCalled();
1953+
expect(driver.create).toHaveBeenCalledTimes(2);
1954+
});
1955+
1956+
it('CONTROL: an item read from another loader still seeds the database loader', async () => {
1957+
const source = new MemoryLoader();
1958+
await source.save('email_template', 'welcome', { name: 'welcome', locale: 'en-US', subject: 'from source', bodyHtml: '<p/>', _packageId: ALPHA });
1959+
await bootPass(source, new DatabaseLoader({ driver }));
1960+
expect(await stored()).toEqual([[ALPHA, null, 'from source']]);
1961+
});
1962+
});

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

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,20 @@ export type WatchCallback = (event: MetadataWatchEvent) => void | Promise<void>;
130130
* {@link MetadataManager.get} already takes a package beyond the spec's
131131
* signature.
132132
*/
133+
/**
134+
* [#31699 R5-A; epic ruling 6801410166] {@link MetadataManager.register}'s
135+
* options: the spec's {@link MetadataWriteOptions}, plus `skipSourceLoader`.
136+
* With it, an item {@link MetadataManager.loadMany} read from a loader is not
137+
* persisted back into that same loader; every other loader's write is
138+
* unchanged. The boot priming pass sets it, so a boot never writes back a row
139+
* it read from the store it read it from. Class-level, as
140+
* {@link MetadataUnregisterOptions} is.
141+
*/
142+
export interface MetadataRegisterOptions extends MetadataWriteOptions {
143+
/** Skip the write-through to the loader `loadMany` read this very item from. */
144+
skipSourceLoader?: boolean;
145+
}
146+
133147
export interface MetadataUnregisterOptions extends MetadataWriteOptions {
134148
/** The package whose item is removed; see the interface doc. */
135149
packageId?: string;
@@ -444,6 +458,8 @@ function redactServedDocument(
444458
*/
445459
export class MetadataManager implements IMetadataService {
446460
private loaders: Map<string, MetadataLoader> = new Map();
461+
/** [#31699 R5-A] The loader {@link loadMany} read each item object from ({@link MetadataRegisterOptions}). */
462+
private readonly loadedFrom = new WeakMap<object, MetadataLoader>();
447463
// Protected so subclasses can access serializers if needed
448464
protected serializers: Map<MetadataFormat, MetadataSerializer>;
449465
protected logger: Logger;
@@ -898,7 +914,7 @@ export class MetadataManager implements IMetadataService {
898914
type: string,
899915
name: string,
900916
data: unknown,
901-
options?: MetadataWriteOptions,
917+
options?: MetadataRegisterOptions,
902918
): Promise<void> {
903919
// [#7378] The ruled register contract, before anything is touched: refuse
904920
// a data.name that disagrees with the name argument and refuse a
@@ -943,6 +959,8 @@ export class MetadataManager implements IMetadataService {
943959
// and because `save?` stays optional on the interface for the protocols
944960
// the gate does not cover. Mirrors the same guard in `unregister()`.
945961
if (typeof loader.save !== 'function') continue;
962+
// [#31699 R5-A] Never back into the loader this item was read from.
963+
if (options?.skipSourceLoader && data !== null && typeof data === 'object' && this.loadedFrom.get(data) === loader) continue;
946964
await loader.save(type, name, data);
947965
}
948966

@@ -3357,12 +3375,14 @@ export class MetadataManager implements IMetadataService {
33573375
if (bundleEntries.has(bundleKey)) continue;
33583376
bundleEntries.add(bundleKey);
33593377
results.push(item);
3378+
if (item !== null && typeof item === 'object') this.loadedFrom.set(item, loader);
33603379
continue;
33613380
}
33623381
const exists = results.some((r: any) => r && r.name === itemAny.name);
33633382
if (exists) continue;
33643383
}
33653384
results.push(item);
3385+
if (item !== null && typeof item === 'object') this.loadedFrom.set(item, loader);
33663386
}
33673387
this.reportLoaderReadRecovered(loader.contract.name);
33683388
} catch (e) {

‎packages/metadata/src/plugin.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1672,7 +1672,10 @@ export class MetadataPlugin implements Plugin {
16721672
// has cached a definition to go stale. Post-boot
16731673
// edits to these files reach watchers through the
16741674
// FileSystemRepository attached by onEnable.
1675-
await this.manager.register(entry.type, meta.name, item, { notify: false });
1675+
// [#31699 R5-A] Never written back into the loader it was read from
1676+
// (a stored row stays as stored); every other loader still receives it,
1677+
// so a file-system item still seeds the database loader.
1678+
await this.manager.register(entry.type, meta.name, item, { notify: false, skipSourceLoader: true });
16761679
}
16771680
}
16781681
ctx.logger.info(`Loaded ${items.length} ${entry.type} from file system`);

0 commit comments

Comments
 (0)